我的小镇校园手机版
55.99 MB · 2025-12-17
在项目开发中,我们常会通过url传参,但是如果遇到中文获取就回乱码,如:传递参数中带有中文url?aaa=你好啊用js获取aaa并显示到页面上出现乱码。该怎么解决呢?
function getQueryString(key){ var reg = new RegExp("(^|&)"+key+"=([^&]*)(&|$)"); var result = window.location.search.substr(1).match(reg); return result?decodeURIComponent(result[2]):null; }
window.search取到的是queryString,如:?a=2&b=3
如url为:
console.log(getQueryString('a'));//2console.log(getQueryString('b'));//3
这里有个地方要说明:decodeURI() 与 encodeURI();decodeURIComponent() 与 encodeURIComponent() 配对使用
不出现乱码也是因为使用了 decodeURIComponent 函数,网上大部分的代码都没有进行中午乱码的处理。