关于获取地址携带的参数以及encodeURI()和encodeURIComponent()编码问题

438 阅读1分钟

项目中常常会把参数携带在地址上,如何更好的携带参数和使用参数?


//JS获取URL中参数值的方法
function getQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.slice(1).match(reg);
    if (r != null) return decodeURIComponent(r[2]);
    return null;
}

//示例
var URL = 'https://www.xxx.com/s?wd=a&rsv_spt=1&backURL='+encodeURIComponent('https://www.xxx.com/s?wd=a&rsv_spt=1')
//JS获取URL中参数值的方法
function getQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = URL.slice(1).match(reg);
    if (r != null) return decodeURIComponent(r[2]);
    return null;
}
console.log(getQueryString('backURL'))
//https://www.xxx.com/s?wd=a&rsv_spt=1

带字符特别带?的参数一定得用encodeURI()和encodeURIComponent()加密

如何合理使用encodeURI()和encodeURIComponent()

项目中遇到过一个问题,后端接口文档中要求使用encodeURI()对中文转义,测试环境正常,但是正式环境中文带了字符,例如“#琉璃第七集”,导致请求失败。

项目是在机顶盒运行的,分析起来比较麻烦,经过抓网络包和日志发现URL的长度不对,意识到是encodeURI这个方法的问题。

encodeURI()是对整个URL进行编码,特殊含义的符号"; / ? : @ & = + $ , #“不进行编码

encodeURIComponent()是对URL的组成部分进行个别编码,所以”; / ? : @ & = + $ , #"在这里是可以进行编码

微信小程序页面webview页面路径中只能带一个参数,所有得把整个URL进行encodeURIComponent()