js 获取URL参数时中文出现乱码状态

版权声明:版权: https://blog.csdn.net/sinat_41661009/article/details/80661889

function getQueryString(name) {   
      var reg = new RegExp( " (^|&) " + name + " = ([^&]*)(&|$) " );   
      var r = window.location.search.substr( 1 ).match( reg );   
      if( r != null ) return unescape( r[2] ); return null;   

}

在使用这个小插件的时候,url 中参数如果有中文的情况下,就会出现中文乱码,通过查阅资料得知,浏览器默认使用的是 encodeURL 对汉字进行编码的,所以在解码的时候就需要使用 decodeURL 而不是上诉代码中的 unescape,只要将上诉代码中 unescape 修改为 decodeURL 就可以解决中文乱码问题了。

function getQueryString(name) {   
      var reg = new RegExp( " (^|&) " + name + " = ([^&]*)(&|$) " );   
      var r = window.location.search.substr( 1 ).match( reg );   
      if( r != null ) return decodeURL( r[2] ); return null;   

}


猜你喜欢

转载自blog.csdn.net/sinat_41661009/article/details/80661889