在Javascript中,如何获取URL字符串(而不是当前URL)的参数?
喜欢:
www.domain.com/?v=123&p=hello
我可以在JSON对象中获取“ v”和“ p”吗?
您可以放心使用Array.forEach。如@ricosrealm所建议,decodeURIComponent在此函数中使用了它。
Array.forEach
decodeURIComponent
function getJsonFromUrl(url) { if(!url) url = location.search; var query = url.substr(1); var result = {}; query.split("&").forEach(function(part) { var item = part.split("="); result[item[0]] = decodeURIComponent(item[1]); }); return result; }
实际上不是那么简单 ,请参阅注释中的同行评审,尤其是:
=
+
也许这应该去codereview SE,但这是更安全和无正则表达式的代码:
function getJsonFromUrl(url) { if(!url) url = location.href; var question = url.indexOf("?"); var hash = url.indexOf("#"); if(hash==-1 && question==-1) return {}; if(hash==-1) hash = url.length; var query = question==-1 || hash==question+1 ? url.substring(hash) : url.substring(question+1,hash); var result = {}; query.split("&").forEach(function(part) { if(!part) return; part = part.split("+").join(" "); // replace every + with space, regexp-free version var eq = part.indexOf("="); var key = eq>-1 ? part.substr(0,eq) : part; var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : ""; var from = key.indexOf("["); if(from==-1) result[decodeURIComponent(key)] = val; else { var to = key.indexOf("]",from); var index = decodeURIComponent(key.substring(from+1,to)); key = decodeURIComponent(key.substring(0,from)); if(!result[key]) result[key] = []; if(!index) result[key].push(val); else result[key][index] = val; } }); return result; }
此功能甚至可以解析URL
var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c"; // {"foo e": ["a a", "c", "[x]":"b"]} var obj = getJsonFromUrl(url)["foo e"]; for(var key in obj) { // Array.forEach would skip string keys here console.log(key,":",obj[key]); } /* 0 : a a 1 : c [x] : b */