在我们进入主题前,我先先看下获取网址URL的方法:
window.location.href//设置或获取整个URL为字符串
window.location.hash//设置或获取href属性中在井号#后面的部分参数
window.location.search//设置或获取href属性中跟在问号?后面,井号#前面的部分参数
例如我们这里有一个url,例如:http://127.0.0.1:8080/html/urltojson.html?id=1&name=good#&price=1003
下面看下上面三个方法是如何使用的
console.log(window.location.href);
//http://127.0.0.1:8080/html/urltojson.html?id=1&name=good#&price=1003
console.log(window.location.hash);
//#&price=1003
console.log(window.location.search);
//?id=1&name=good
我们看到了上面三个方法的返回参数是不一样的,我们接下来看下如果将url转换为json格式的数据。
第一种:for循环方式
//第一种:for循环
varGetQueryJson1=function(){
leturl=location.href;//获取当前浏览器的URL
letarr=[];//存储参数的数组
letres={};//存储最终JSON结果对象
arr=url.split('?')[1].split('&');//获取浏览器地址栏中的参数
for(leti=0;i<arr.length;i++){//遍历参数
if(arr[i].indexOf('=')!=-1){//如果参数中有值
letstr=arr[i].split('=');
res[str[0]]=str[1];
}else{//如果参数中无值
res[arr[i]]='';
}
}
returnres;
}
console.log(GetQueryJson1());
第二种:正则表达式方式
//第二种:正则表达式
varGetQueryJson2=function(){
leturl=location.href;//获取当前浏览器的URL
letparam={};//存储最终JSON结果对象
url.replace(/([^?&]+)=([^?&]+)/g,function(s,v,k){
param[v]=decodeURIComponent(k);//解析字符为中文
returnk+'='+v;
});
returnparam;
}
console.log(GetQueryJson2());
以上所述是小端给大家介绍的JS将网址url转化为JSON格式的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言
如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h56607.shtml