当需要通过查询字符串传值给服务器时需要对get参数进行转义。
escape()
函数,不会转义 @*/+
(已废弃)encodeURI()
函数,不会转义 ~!@#$&*()=:/,;?+'
(不推荐使用),解码用decodeURIencodeURIComponent()
函数,不会转义 ~!*()
这个函数是最常用的,解码用decodeURIComponent
我们需要对encodeURIComponent函数,最一点修改:
function urlencode (str) {
str = (str + '').toString();
return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}
PS:例如微信H5支付中要求对回调页面的参数redirect_url参数进行 URLEncode。
前端路由采用了hash模式,由于我采用的是encodeURI,导致 # 未转义而引起#后面内容的丢失,采用encodeURIComponent就好了
转载文章,本文观点不代表本站立场