如何在 Javascript 中解析 URL 查询参数? [英] How do I parse a URL query parameters, in Javascript?
问题描述
可能的重复:
在javascript中使用url的get参数
如何在 JavaScript 中获取查询字符串值?
在 Javascript 中,如何获取 URL 字符串的参数(不是当前 URL)?
In Javascript, how can I get the parameters of a URL string (not the current URL)?
喜欢:
www.domain.com/?v=123&p=hello
我可以在 JSON 对象中获取v"和p"吗?
Can I get "v" and "p" in a JSON object?
推荐答案
今天(这个答案 2.5 年后)你可以 安全使用 Array.forEach
.正如@ricosrealm 所建议的,在这个函数中使用了 decodeURIComponent
.
Today (2.5 years after this answer) you can safely use Array.forEach
. As @ricosrealm suggests, decodeURIComponent
was used in this function.
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;
}
其实没那么简单,看评论里的同行评议,特别是:
actually it's not that simple, see the peer-review in the comments, especially:
- 基于哈希的路由 (@cmfolio)
- 数组参数 (@user2368055)
- 正确使用 decodeURIComponent 和未编码的
=
(@AndrewF) - 非编码
+
(由我添加)
- hash based routing (@cmfolio)
- array parameters (@user2368055)
- proper use of decodeURIComponent and non-encoded
=
(@AndrewF) - non-encoded
+
(added by me)
有关更多详细信息,请参阅 MDN 文章 和 RFC 3986.
For further details, see MDN article and RFC 3986.
也许这应该转到 codereview SE,但这里是更安全且无正则表达式的代码:
Maybe this should go to codereview SE, but here is safer and regexp-free code:
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;
}
这个函数甚至可以解析像
This function can parse even URLs like
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
*/
这篇关于如何在 Javascript 中解析 URL 查询参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!