javascript将对象转换为url参数
function filter(str) { // 特殊字符转义 str += ''; // 隐式转换 str = str.replace(/%/g, '%25'); str = str.replace(/\+/g, '%2B'); str = str.replace(/ /g, '%20'); str = str.replace(/\//g, '%2F'); str = str.replace(/\?/g, '%3F'); str = str.replace(/&/g, '%26'); str = str.replace(/\=/g, '%3D'); str = str.replace(/#/g, '%23'); return str; } function formateObjToParamStr(paramObj) { const sdata = []; for (let attr in paramObj) { sdata.push(`${attr}=${filter(paramObj[attr])}`); } return sdata.join('&'); };
const data = {id: '3', name:"chenjianbin", ojb: '3232'} console.log(formateObjToParamStr(data)) // 返回 id=3&name=chenjianbin&ojb=3232
参考原址 https://www.jianshu.com/p/9c464845ca5b