是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
当前回答
tl;博士
一个快速、完整的解决方案,可处理多值键和编码字符。
// using ES5 (200 characters)
var qd = {};
if (location.search) location.search.substr(1).split("&").forEach(function(item) {var s = item.split("="), k = s[0], v = s[1] && decodeURIComponent(s[1]); (qd[k] = qd[k] || []).push(v)})
// using ES6 (23 characters cooler)
var qd = {};
if (location.search) location.search.substr(1).split`&`.forEach(item => {let [k,v] = item.split`=`; v = v && decodeURIComponent(v); (qd[k] = qd[k] || []).push(v)})
// as a function with reduce
function getQueryParams() {
return location.search
? location.search.substr(1).split`&`.reduce((qd, item) => {let [k,v] = item.split`=`; v = v && decodeURIComponent(v); (qd[k] = qd[k] || []).push(v); return qd}, {})
: {}
}
多行:
var qd = {};
if (location.search) location.search.substr(1).split("&").forEach(function(item) {
var s = item.split("="),
k = s[0],
v = s[1] && decodeURIComponent(s[1]); // null-coalescing / short-circuit
//(k in qd) ? qd[k].push(v) : qd[k] = [v]
(qd[k] = qd[k] || []).push(v) // null-coalescing / short-circuit
})
这是什么代码。。。“零合并”,短路评估ES6解构赋值、箭头函数、模板字符串####示例:
"?a=1&b=0&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"
> qd
a: ["1", "5", "t e x t"]
b: ["0"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]
> qd.a[1] // "5"
> qd["a"][1] // "5"
阅读更多。。。关于Vanilla JavaScript解决方案。
要访问URL的不同部分,请使用位置。(搜索|哈希)
最简单(虚拟)解决方案
var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
正确处理空钥匙。使用找到的最后一个值覆盖多键。
"?a=1&b=0&c=3&d&e&a=5"
> queryDict
a: "5"
b: "0"
c: "3"
d: undefined
e: undefined
多值键
简单的密钥检查(字典中的项目)?dict.item.push(val):dict.item=[val]
var qd = {};
location.search.substr(1).split("&").forEach(function(item) {(item.split("=")[0] in qd) ? qd[item.split("=")[0]].push(item.split("=")[1]) : qd[item.split("=")[0]] = [item.split("=")[1]]})
现在返回数组。按qd.key[index]或qd[key][index]访问值
> qd
a: ["1", "5"]
b: ["0"]
c: ["3"]
d: [undefined]
e: [undefined]
编码字符?
对第二次或两次拆分使用decodeURIComponent()。
var qd = {};
location.search.substr(1).split("&").forEach(function(item) {var k = item.split("=")[0], v = decodeURIComponent(item.split("=")[1]); (k in qd) ? qd[k].push(v) : qd[k] = [v]})
####示例:
"?a=1&b=0&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"
> qd
a: ["1", "5", "t e x t"]
b: ["0"]
c: ["3"]
d: ["undefined"] // decodeURIComponent(undefined) returns "undefined" !!!*
e: ["undefined", "http://w3schools.com/my test.asp?name=ståle&car=saab"]
v = v && decodeURIComponent(v);
if (location.search) location.search.substr(1).split("&").forEach(...)
其他回答
我接受了这个答案,并添加了对可选地将URL作为参数传入的支持;返回到window.location.search。显然,这对于从不是当前页面的URL获取查询字符串参数非常有用:
(function($, undef) {
$.QueryString = function(url) {
var pairs, qs = null, index, map = {};
if(url == undef){
qs = window.location.search.substr(1);
}else{
index = url.indexOf('?');
if(index == -1) return {};
qs = url.substring(index+1);
}
pairs = qs.split('&');
if (pairs == "") return {};
for (var i = 0; i < pairs.length; ++i)
{
var p = pairs[i].split('=');
if(p.length != 2) continue;
map[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return map;
};
})(jQuery);
Node.js的源代码中有一个健壮的实现https://github.com/joyent/node/blob/master/lib/querystring.js
TJ的qs也执行嵌套参数解析https://github.com/visionmedia/node-querystring
我宁愿使用split()而不是Regex执行此操作:
function getUrlParams() {
var result = {};
var params = (window.location.search.split('?')[1] || '').split('&');
for(var param in params) {
if (params.hasOwnProperty(param)) {
var paramParts = params[param].split('=');
result[paramParts[0]] = decodeURIComponent(paramParts[1] || "");
}
}
return result;
}
我需要查询字符串中的一个对象,我讨厌很多代码。它可能不是世界上最健壮的,但它只是几行代码。
var q = {};
location.href.split('?')[1].split('&').forEach(function(i){
q[i.split('=')[0]]=i.split('=')[1];
});
像这样的URL.htm?hello=world&foo=bar将创建:
{hello:'world', foo:'bar'}
如果您使用的是jQuery,那么可以使用一个库,例如jQueryBBQ:返回按钮和查询库。
…jQueryBBQ提供了一个完整的.depam()方法,以及哈希状态管理、片段/查询字符串解析和合并实用程序方法。
编辑:添加参数示例:
var DeparamExample=函数(){var params=$.depam.querystring();//nameofram是来自url的参数的名称//如果ajax使用哈希刷新,下面的代码将获取参数if(typeof params.nameofram==“undefined”){params=jQuery.departam.frage(window.location.href);}if(typeof params.nameofram!=“undefined”){var paramValue=params.nameofram.toString();}};
如果您只想使用纯JavaScript,可以使用。。。
var getParamValue = (function() {
var params;
var resetParams = function() {
var query = window.location.search;
var regex = /[?&;](.+?)=([^&;]+)/g;
var match;
params = {};
if (query) {
while (match = regex.exec(query)) {
params[match[1]] = decodeURIComponent(match[2]);
}
}
};
window.addEventListener
&& window.addEventListener('popstate', resetParams);
resetParams();
return function(param) {
return params.hasOwnProperty(param) ? params[param] : null;
}
})();
由于新的HTML历史API,特别是History.pushState()和History.replaceState(),URL可能会发生更改,这将使参数及其值的缓存无效。
此版本将在每次更改历史记录时更新其内部参数缓存。