js解决url传递中文参数乱码问题的方法详解

https://www.jb51.net/article/283636.htm 原文链接

场景复现:
bug解决思路:

url传参中文乱码的解决方法
1、escape 和 unescape
2、encodeURI 和 decodeURI
3、encodeURIComponent 和 decodeURIComponent

总结

1、escape 和 unescape

escape()不能直接用于URL编码,它的真正作用是返回一个字符的Unicode编码值。

采用unicode字符集对指定的字符串除0-255以外进行编码。所有的空格符、标点符号、特殊字符以及更多有联系非ASCII字符都将被转化成%xx格式的字符编码(xx等于该字符在字符集表里面的编码的16进制数字)。比如,空格符对应的编码是%20。
escape不编码字符有69个:*,+,-,.,/,@,_,0-9,a-z,A-Z。

escape()函数用于js对字符串进行编码,不常用。

//跳转页
location.href = './test.html?'+escape('name=张三&age=18')
//接收页
var str = unescape(location.search.substr(1));
//url显示
'test.html?name%3D%u5F20%u4E09%26age%3D18'

2、encodeURI 和 decodeURI

把URI字符串采用UTF-8编码格式转化成escape各式的字符串。

encodeURI不编码字符有82个:!,#,$,&,',(,),*,+,,,-,.,/,:,;,=,?,@,_,~,0-9,a-z,A-Z

encodeURI()用于整个url编码。

//跳转页
location.href = encodeURI('./test.html?name=张三&age=18');
//接收页
var str = decodeURI(location.search.substr(1));
//url显示
'test.html?name=张三&age=18'

3、encodeURIComponent 和 decodeURIComponent

与encodeURI()的不同的是,“; / ? : @ & = + $ , #”,这些在encodeURI()中不被编码的符号,在encodeURIComponent()中统统会被编码。至于具体的编码方法,两者是一样。把URI字符串采用UTF-8编码格式转化成escape格式的字符串。

//跳转页
location.href = './test.html?'+encodeURIComponent('name=张三&age=18');
//接收页
var str = decodeURIComponent(location.search.substr(1));
//url显示
'test.html?name%3D张三%26age%3D18'
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值