如何在Javascript中解析URL查询参数?(复制)
Possible Duplicate:
Use the get paramater of the url in javascript
Get query string values in JavaScript可能的复制:在javascript中使用url的get paramater获取查询字符串值。
In Javascript, how can I get the parameters of a URL string (not the current URL)?
在Javascript中,如何获取URL字符串的参数(不是当前URL)?
like:
如:
www.domain.com/?v=123&p=hello
Can I get "v" and "p" in a JSON object?
我能在JSON对象中得到v和p吗?
3 个解决方案
#1
74
Today (2.5 years after this answer) you can safely use Array.forEach
. As @ricosrealm suggests, decodeURIComponent
was used in this function.
今天(在这个答案之后的2.5年),你可以安全地使用Array.forEach。正如@ricosrealm所建议的,该函数中使用了decodeURIComponent。
function getJsonFromUrl() {
var query = location.search.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:
实际上并不是那么简单,请在评论中看到同行评议,特别是:
- hash based routing (@cmfolio)
- 基于哈希的路由(@cmfolio)
- array parameters (@user2368055)
- 数组参数(@user2368055)
- proper use of decodeURIComponent (@AndrewF)
- 正确使用decodeURIComponent (@AndrewF)
Maybe this should go to codereview SE, but here is safer and regexp-free code:
也许这应该去codereview SE,但这里有更安全的和regexpfree代码:
function getJsonFromUrl(hashBased) {
var query;
if(hashBased) {
var pos = location.href.indexOf("?");
if(pos==-1) return [];
query = location.href.substr(pos+1);
} else {
query = location.search.substr(1);
}
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;
}
I also replaced non-encoded +
for space according to this article which is also useful guide how to encode adhering to RFC 3986.
我还根据这篇文章替换了非编码的+空间,这也是如何编码遵循RFC 3986的有用指南。
Note the result[key][index] = val
: a new array item is created, it is enumerable, so it can be iterated by forEach
call. Therefore, you can parse even URLs like
注意结果[key][index] = val:创建了一个新的数组项,它是可枚举的,因此可以通过forEach调用迭代它。因此,您甚至可以解析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
*/
更多相关文章
- 字体图标的引入和通过媒体查询改变导航样式
- HTML样式和常用选择器
- 字体图标的引用和自定义样式/媒体查询的使用
- 数据库的CURD操作、PDO本质与原理的学习
- CSS之伪类选择器和简单盒子简单案例
- 伪类选择器与盒模型常用属性
- 伪类选择器-结构伪类、根据位置选择匹配
- 7.4——常用标签与应用场景之表格与单元格
- css伪类选择器和盒模型