JavaScript之location.search中文乱码的问题

xiaoxiao2021-02-28  45

JavaScript的location.search返回URL的查询字符串,这个字符串以问号开头,如下图就是该方法返回的查询字符串:

获取并解析查询字符串的方法:

function getQueryStringArgs() { var qs = (location.search.length>0 ? location.search.substring(1):""), args = {}, items = qs.length ? qs.split("&") : [], item = null, name = null, value = null, i=0, len = items.length; for(i=0;i<len;i++){ item = item[i].split("="); name = decodeURIComponent(item[0]); value = decodeURIComponent(item[1]);//执行解码,因为中文字符串往往在传递时被编码过了 if(name.length) args[name]=value; } return args;//args["userid"]=叶倩 } decodeURIComponent() 解码是关键,如果不解码有可能获取到的userid是一堆被编码过的字符串。
转载请注明原文地址: https://www.6miu.com/read-2614850.html

最新回复(0)