对象转为url地址参数
ajax请求中url地址上参数的封装函数
//用&拼接对象成字符串
function getParams(params) {
let paramStr = '';
Object.keys(params)
.forEach((item) => {
if (paramStr === '') {
paramStr = `${item}=${params[item]}`;
} else {
paramStr = `${paramStr}&${item}=${params[item]}`;
}
});
console.log(paramStr);
return paramStr;
}
let params={a:1,b:2}
getParams(params) //输出:a=1&b=2
将url拆分为对象
function getParams(url) {
var obj = {};
if (url.indexOf('?') != -1) {
var temp1 = url.split('?');
var pram = temp1[1];
var keyValue = pram.split('&');
for (var i = 0; i < keyValue.length; i++) {
var item = keyValue[i].split('=');
var key = item[0];
var value = item[1];
obj[key] = value;
}
}
return obj;
}
let a="qwe?www=111&qqq=222"
console.log(getParams(a));//{www: "111", qqq: "222"}