> 文档中心 > 前端Url 传参编码

前端Url 传参编码


背景

我遇到的问题是这样

例如:我的用户中心的项目是这样的URL:https://my.csdn.net/我的一个活动页的项目的URL是:https://my.csdn.net/?id=1166这个时候我需要进活动页报名,活动页是需要登录的登录后必须返回活动页,最终的连接跳转应该是这样的https://my.csdn.net/?returnUrl=https://my.csdn.net/?id=1166但是这样跳转的URL在获取returnUrl时会出错  所以需要对returnUrl的值进行编码如下:链接编码:encodeURIComponent()编码链接解码:decodeURIComponent()解码防止​url加密传参有时候会出现Uncaught URIError: URI malformed的错误​跳转的时候处理如下:window.location.href = decodeURIComponent(returnUrl.replace(/%/g,'%25'));//使用returnUrl 跳转时必须使用decodeURIComponent()解码

 


文字编码:escape()编码
文字解码:unescape()解码

链接编码:encodeURIComponent()编码
链接解码:decodeURIComponent()解码

在使用时你可以遇到这样的错误

Uncaught URIError: URI malformed

url加密传参有时候会出现Uncaught URIError: URI malformed的错误,这是因为你的url中包含了“%”字符,浏览器在对“%”执行decodeURIComponent时报错,正确的解决是将%全部替换为%25再进行传输:

const percent2percent25 = (URI) => {  if(URI.indexOf('%') > -1) {    return URI.replace(/%/g,'%25')  }else{    return URI;  }}


 延伸阅读

c#对js的encodeURI() 编码 decodeURI()解码 escape() 编码unescape()解码,decodeURIComponent() ,encodeURICompon加密解密_cplvfx的博客-CSDN博客_js url编码c#对js的encodeURI() 编码 decodeURI()解码 ,escape() 编码unescape()解码,encodeURIComponent()编码 decodeURIComponent() 解码,字符串加密解密https://blog.csdn.net/cplvfx/article/details/116644635

js对url和字符串,解码,编码,解密,加密_cplvfx的博客-CSDN博客_js url加密和解密decodeURI() 函数可对 encodeURI() 函数编码过的 URI 进行解码。var uri="my test.php?name=你好&car=saab";document.write(encodeURI(uri)+ "
");//编码document.write(decodeURI(uri));//解码结果my%20test.php?name=%E4%BD%A0%E5%A5%BD&car=saabmy test.php?name=你好
https://blog.csdn.net/cplvfx/article/details/114586854