拼装url的查询字段
let params = {
start_time: '2018-07-16';
end_time: '2018-07-16'
};
params = Object.keys(params).map(function (key) {
if(typeof params[key] === 'object'){
params[key] = JSON.stringify(params[key]);
}
return encodeURIComponent(key) + "=" + encodeURIComponent(params[key]);
}).join("&");
或
function generateUrl(url, params){
var newUrl = url + '?';
for(var key in params){
newUrl += (key + '=' + params[key] + '&');
}
return newUrl.substring(0, newUrl.length - 1);
}
获取url的查询字段
** 通过location.search获取?x1=a&x2=b..
,通过location.href获取整个url;**
function getQuerys(url) {
url = decodeURIComponent(url);
let params = {};
if (url.indexOf('?') !== -1) {
let res = url.split('?')[1].split('&');
res.forEach(item => {
params[item.split('=')[0]] = item.split('=')[1];
});
}
return params;
}
//调用
getQuerys(location.href);
使用正则的方式
function getQuerys(url){
url = url.split('?')[1];
let params = {};
let arr = url.match(/(^|&)\w+=([^&]*)/g).join('').split('&');
arr.forEach(item => {
params[item.split('=')[0]] = item.split('=')[1];
});
return params;
}
//调用
getQuerys(location.href);
网友评论