序列化
方式一
/** 将对象转换成 URL 参数** 空格 --> %20* + --> %2B* Content-Type: application/x-www-form-urlencoded* */const encodedUrlParams = obj => {let arr = [];for(let i in obj){if (obj.hasOwnProperty(i)) {arr.push(encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]));}}return arr.join("&");};
方式二
/** 空格 --> ++* + --> %2B* Content-Type: application/x-www-form-urlencoded;charset=UTF-8* */const encodedUrlParams2 = obj => { // 方式二let data = new URLSearchParams();for(let i in obj) {if(obj.hasOwnProperty(i)) {data.append(i, obj[i]);}}return data;};
反序列化
将 URL 参数转换为对象
const urlToObj = url => {let string = url.split('&');let res = {};for(let i = 0;i<string.length;i++){let str = string[i].split('=');if(str[0]!=''){res[str[0]]=str[1];}}return res;}//调用urlToObj("a=1&b=2")
