不知道大家有没有这样的困扰,汉字转码问题,因为浏览器会对汉字自动转码,并且某些302之后可能又转码了一次,并且有的值在各种页面的url上传递,传来传去,前端可能也不知道究竟转码了几次,然后后端就蒙蔽了,明明解码了呀,balabala。其实个人觉得最好尽量少使用汉字作为参数传递。不过要是必须用也是有办法的,那就是循环调用decodeURIComponent
,直到转换完的和上一次的值是一样的为止,使用decodeURIComponent
时可能会报错,比如转码8%
,意思是百分之8,但是decodeURIComponent
对百分号敏感,所以需要用try catch 捕获异常,当error发生时,也停止继续decodeURIComponent
,具体代码如如下:
function decode(pre) {
function isEqual(pre, cur) {
return pre === cur
}
function decodeURIComponent(str) {
try {
return window.decodeURIComponent(str)
} catch (err) {
return str
}
}
let cur = decodeURIComponent(pre)
while (!isEqual(pre, cur)) {
pre = cur
cur = decodeURIComponent(cur)
}
return cur
}