解析url ? 之后的参数
方法1:
getUrlParam: function () {
// 解析路由?之后的字符串
var querystring = location.search.substr(1);
// querystring => 'id=8&name=zhangsan'
var pairs = querystring.split('&');
// pairs => [ 'id=8', 'name=zhangsan' ]
var query = {};
pairs.forEach(function (item) {
// item => 'id=8'
var kv = item.split('=');
// kv => [ 'id', '8' ]
var key = kv[0];
// key => 'id'
query[key] = kv[1];
// query['id'] = '8'
})
// 这里是对字符串进行解码
var urlStr = decodeURIComponent(query.param);
// 这里是对解码后的字符串转对象
this.urlParam = JSON.parse(urlStr);
// console.log(this.urlParam)
// this.urlParam.projectId = '3301100001'
// console.log(this.urlParam)
},
方法2:
function parseQueryString(url) {
var params = {};
var arr = url.split("?");
if (arr.length <= 1) {
return params;
}
arr = arr[1].split("&");
for (var i = 0, l = arr.length; i < l; i++) {
var a = arr[i].split("=");
params[a[0]] = a[1];
}
return params;
}
// var url = location.search.substr(1);
var url = "http://www.baidu.com?key0=0&key1=1&key2=2";
var ps = parseQueryString(url);
console.log(ps)