JavaScript query string
Is there any JavaScript library that makes a dictionary out of the query string, ASP.NET
style?
Something which can be used like:
var query = window.location.querystring["query"]?
Is "query string" called something else outside the .NET
realm? Why isn't location.search
broken into a key/value collection ?
EDIT : I have written my own function, but does any major JavaScript library do this?
Maybe http://plugins.jquery.com/query-object/?
This is the fork of it https://github.com/sousk/jquery.parsequery#readme.
You can extract the key/value pairs from the location.search property, this property has the part of the URL that follows the ? symbol, including the ? symbol.
function getQueryString() {
var result = {}, queryString = location.search.slice(1),
re = /([^&=]+)=([^&]*)/g, m;
while (m = re.exec(queryString)) {
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
return result;
}
// ...
var myParam = getQueryString()["myParam"];
tl;dr solution on a single(ish) line of code using vanilla javascript
var queryDict = {}
location.search.substr(1).split("&").forEach(function(item) {
queryDict[item.split("=")[0]] = item.split("=")[1]
})
For querystring ?a=1&b=2&c=3&d&e
it returns:
> queryDict
a: "1"
b: "2"
c: "3"
d: undefined
e: undefined
multi-valued keys and encoded characters?
See the original answer at How can I get query string values in JavaScript?
"?a=1&b=2&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab"
> queryDict
a: ["1", "5", "t e x t"]
b: ["2"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]
链接地址: http://www.djcxy.com/p/2904.html
上一篇: 重复HTTP GET查询键的权威位置
下一篇: JavaScript查询字符串