js 解析url中search时存在中文乱码问题解决方案

一 问题出现原因

当存在这样一种需求,前端需要通过url中search返回值进行保存使用,但如果search中存在中文解析出来会导致乱码。这个问题我找了很久原因,最后终于知道解决方案,这里和大家分享一下。

二 解决方案

使用decodeURIComponent() 函数对其存在中文部分解码操作。

三 认识decodeURIComponent

URI: Uniform ResourceIdentifiers,通用资源标识符
Global对象的encodeURI()和encodeURIComponent()方法可以对URI进行编码,以便发送给浏览器。有效的URI中不能包含某些字符,例如空格。而这URI编码方法就可以对URI进行编码,它们用特殊的UTF-8编码替换所有无效的字 符,从而让浏览器能够接受和理解。
其中encodeURI()主要用于整个URI(例如,http://www.jxbh.cn/illegal value.htm),而encode-URIComponent()主要用于对URI中的某一段(例如前面URI中的illegal value.htm)进行编码。它们的主要区别在于,encodeURI()不会对本身属于URI的特殊字符进行编码,例如冒号、正斜杠、问号和井字号;而encodeURIComponent()则会对它发现的任何非标准字符进行编码。来看下面的例子:
var uri="http://www.jxbh.cn/illegal value.htm#start";
//”http: //www.jxbh.cn/illegal value .htm#s tart”
alert(encodeURI (uri)):
//”http% 3A%2F%2Fwww.jxbh.cn%2 Fillegal%2 0value. htm%23 start”
alert( encodaURIComponent (uri));
使用encodeURI()编码后的结果是除了空格之外的其他字符都原封不动,只有空格被替换成了%20。而encodeURIComponent()方法则会使用对应的编码替换所有非字母数字字符。这也正是可以对整个URI使用encodeURI(),而只能对附加在现有URI后面的字符串使用encodeURIComponent()的原因所在。一般来说,我们使用encodeURIComponent()方法的时候要比使用encodeURI()更多,因为在实践中更常见的是对查询字符串参数而不是对基础URL进行编码.
经我的观测,很多网站的cookie在进行编码的时候,是encodeURIComponent格式的,所以应该使用decodeURIComponent()进行解码

四 解析search函数

//获取url中"?"符后的字串
var getRequest =function() {
  var url = window.location.search;
  var strs = [];
  var theRequest = new Object();
  if (url.indexOf("?") != -1) {
    var str = url.substr(1);
     strs = str.split("&");
    for(var i = 0; i < strs.length; i ++) {
      theRequest[strs[i].split("=")[0]]=decodeURIComponent(strs[i].split("=")[1]);
    }
  }
  return theRequest;
};
原文地址:https://www.cnblogs.com/honkerzh/p/10647584.html