是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
当前回答
这是Andy E链接的“句柄数组样式查询字符串”版本的扩展版本。修复了一个错误(?key=1&key[]=2&key[]=3;1丢失并替换为[2,3]),进行了一些小的性能改进(重新解码值,重新计算“[”位置等),并添加了一些改进(功能化,支持?key=1&key=2,支持;分隔符)。我将变量留得很短,但添加了大量注释以使其可读(哦,我在本地函数中重用了v,如果这令人困惑,很抱歉;)。
它将处理以下查询字符串。。。
?test=Hello&pers=neek&pers[]=jeff&pers[][]=jim&pers[extra]=john&test3&nocache=13989148914891264
…把它做成一个看起来像。。。
{
"test": "Hello",
"person": {
"0": "neek",
"1": "jeff",
"2": "jim",
"length": 3,
"extra": "john"
},
"test3": "",
"nocache": "1398914891264"
}
如上所述,此版本处理一些“格式错误”数组,即-person=neek&person[]=jeff&person[]=jim或person=neek/person=jeff/person=jim,因为密钥是可识别的和有效的(至少在dotNet的NameValueCollection.Add中):
如果目标NameValueCollection中已存在指定的键例如,指定的值将添加到现有的逗号分隔的格式为“value1,value2,value3”的值列表。
似乎陪审团对重复的键有点不满意,因为没有规范。在这种情况下,多个键被存储为一个(假)数组。但请注意,我不会将基于逗号的值处理为数组。
代码:
getQueryStringKey = function(key) {
return getQueryStringAsObject()[key];
};
getQueryStringAsObject = function() {
var b, cv, e, k, ma, sk, v, r = {},
d = function (v) { return decodeURIComponent(v).replace(/\+/g, " "); }, //# d(ecode) the v(alue)
q = window.location.search.substring(1), //# suggested: q = decodeURIComponent(window.location.search.substring(1)),
s = /([^&;=]+)=?([^&;]*)/g //# original regex that does not allow for ; as a delimiter: /([^&=]+)=?([^&]*)/g
;
//# ma(make array) out of the v(alue)
ma = function(v) {
//# If the passed v(alue) hasn't been setup as an object
if (typeof v != "object") {
//# Grab the cv(current value) then setup the v(alue) as an object
cv = v;
v = {};
v.length = 0;
//# If there was a cv(current value), .push it into the new v(alue)'s array
//# NOTE: This may or may not be 100% logical to do... but it's better than loosing the original value
if (cv) { Array.prototype.push.call(v, cv); }
}
return v;
};
//# While we still have key-value e(ntries) from the q(uerystring) via the s(earch regex)...
while (e = s.exec(q)) { //# while((e = s.exec(q)) !== null) {
//# Collect the open b(racket) location (if any) then set the d(ecoded) v(alue) from the above split key-value e(ntry)
b = e[1].indexOf("[");
v = d(e[2]);
//# As long as this is NOT a hash[]-style key-value e(ntry)
if (b < 0) { //# b == "-1"
//# d(ecode) the simple k(ey)
k = d(e[1]);
//# If the k(ey) already exists
if (r[k]) {
//# ma(make array) out of the k(ey) then .push the v(alue) into the k(ey)'s array in the r(eturn value)
r[k] = ma(r[k]);
Array.prototype.push.call(r[k], v);
}
//# Else this is a new k(ey), so just add the k(ey)/v(alue) into the r(eturn value)
else {
r[k] = v;
}
}
//# Else we've got ourselves a hash[]-style key-value e(ntry)
else {
//# Collect the d(ecoded) k(ey) and the d(ecoded) sk(sub-key) based on the b(racket) locations
k = d(e[1].slice(0, b));
sk = d(e[1].slice(b + 1, e[1].indexOf("]", b)));
//# ma(make array) out of the k(ey)
r[k] = ma(r[k]);
//# If we have a sk(sub-key), plug the v(alue) into it
if (sk) { r[k][sk] = v; }
//# Else .push the v(alue) into the k(ey)'s array
else { Array.prototype.push.call(r[k], v); }
}
}
//# Return the r(eturn value)
return r;
};
其他回答
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(...)
更新:2022年1月
使用Proxy()比使用Object.fromEntries()更快,并且更受支持
const params = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop),
});
// Get the value of "some_key" in eg "https://example.com/?some_key=some_value"
let value = params.some_key; // "some_value"
更新日期:2021年6月
对于需要所有查询参数的特定情况:
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
更新:2018年9月
您可以使用URLSearchParams,它很简单,并且具有良好(但不完全)的浏览器支持。
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
起初的
为此,您不需要jQuery。您可以使用一些纯JavaScript:
function getParameterByName(name, url = window.location.href) {
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
用法:
// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
var bar = getParameterByName('bar'); // "" (present with empty value)
var baz = getParameterByName('baz'); // "" (present with no value)
var qux = getParameterByName('qux'); // null (absent)
注意:如果参数出现多次(?foo=lorem&foo=ipsum),您将获得第一个值(lorem)。关于这一点没有标准,用法也各不相同,请参见例如这个问题:重复HTTPGET查询键的权威位置。
注意:该函数区分大小写。如果您喜欢不区分大小写的参数名,请在RegExp中添加“i”修饰符
注意:如果您得到了一个无无用转义esint错误,可以替换name=name.replace(/[\[\]]/g,'\\$&');其中name=name。replace(/[[\]]/g,'\\$&')。
这是基于新URLSearchParams规范的更新,以更简洁地实现相同的结果。请参阅下面标题为“URLSearchParams”的答案。
此函数将查询字符串转换为类似JSON的对象,它还处理无值和多值参数:
"use strict";
function getQuerystringData(name) {
var data = { };
var parameters = window.location.search.substring(1).split("&");
for (var i = 0, j = parameters.length; i < j; i++) {
var parameter = parameters[i].split("=");
var parameterName = decodeURIComponent(parameter[0]);
var parameterValue = typeof parameter[1] === "undefined" ? parameter[1] : decodeURIComponent(parameter[1]);
var dataType = typeof data[parameterName];
if (dataType === "undefined") {
data[parameterName] = parameterValue;
} else if (dataType === "array") {
data[parameterName].push(parameterValue);
} else {
data[parameterName] = [data[parameterName]];
data[parameterName].push(parameterValue);
}
}
return typeof name === "string" ? data[name] : data;
}
我们对参数[1]执行未定义检查,因为如果变量未定义,decodeURIComponent将返回字符串“undefined”,这是错误的。
用法:
"use strict";
var data = getQuerystringData();
var parameterValue = getQuerystringData("parameterName");
我喜欢Ryan Phelan的解决方案。但我看不出扩展jQuery有什么意义?没有使用jQuery功能。
另一方面,我喜欢Google Chrome中的内置函数:window.location.getParameter。
那么为什么不使用这个呢?好吧,其他浏览器没有。因此,如果不存在,让我们创建此函数:
if (!window.location.getParameter ) {
window.location.getParameter = function(key) {
function parseParams() {
var params = {},
e,
a = /\+/g, // Regex for replacing addition symbol with a space
r = /([^&=]+)=?([^&]*)/g,
d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
q = window.location.search.substring(1);
while (e = r.exec(q))
params[d(e[1])] = d(e[2]);
return params;
}
if (!this.queryStringParams)
this.queryStringParams = parseParams();
return this.queryStringParams[key];
};
}
该函数或多或少与Ryan Phelan有所不同,但包装方式不同:名称清晰,不依赖其他javascript库。有关此功能的更多信息,请访问我的博客。
我接受了这个答案,并添加了对可选地将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);