是否有一种通过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;
};
其他回答
我使用以下代码(JavaScript)获取通过URL传递的内容:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
然后,要将值分配给变量,只需指定要获取的参数,例如,如果URL是example.com/?I=1&p=2&f=3
您可以执行此操作以获取值:
var getI = getUrlVars()["I"];
var getP = getUrlVars()["p"];
var getF = getUrlVars()["f"];
则值将为:
getI = 1, getP = 2 and getF = 3
获取所有querystring参数,包括复选框值(数组)。
考虑到GET参数的正确和正常使用,我认为在大多数函数中,它缺少的是对数组的支持和删除哈希数据。
所以我写了这个函数:
function qs(a){
if(!a)return {};
a=a.split('#')[0].split('&');
var b=a.length,c={},d,k,v;
while(b--){
d=a[b].split('=');
k=d[0].replace('[]',''),v=decodeURIComponent(d[1]||'');
c[k]?typeof c[k]==='string'?(c[k]=[v,c[k]]):(c[k].unshift(v)):c[k]=v;
}
return c
}
使用速记运算符&while--loop,性能应该非常好。
支持:
空值(key=/key)键值(Key=value)数组(键[]=值)哈希(哈希标签被拆分)
笔记:
它不支持对象数组(key[key]=value)
如果空格为+,则保留为+。
如果需要,添加替换(/\+/g,“”)。
用法:
qs('array[]=1&array[]=2&key=value&empty=&empty2#hash')
返回:
{
"empty": "",
"key": "value",
"array": [
"1",
"2"
]
}
演示:
http://jsfiddle.net/ZQMrt/1/
Info
如果你不明白什么,或者你读不懂函数,就问问。我很高兴解释我在这里做了什么。
如果您认为该函数不可读且无法维护,我很乐意为您重写该函数,但请考虑速记和按位运算符总是比标准语法更快(可能在ECMA-262书中阅读有关速记和按位数运算符的信息,或使用您最爱的搜索引擎)。用标准可读语法重写代码意味着性能损失。
我接受了这个答案,并添加了对可选地将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);
这是我在GitHub上的查询字符串解析代码版本。
它的前缀是jquery.*,但解析函数本身不使用jquery。它非常快,但仍然可以进行一些简单的性能优化。
它还支持URL中的列表和哈希表编码,例如:
arr[]=10&arr[]=20&arr[]=100
or
hash[key1]=hello&hash[key2]=moto&a=How%20are%20you
jQuery.toQueryParams = function(str, separator) {
separator = separator || '&'
var obj = {}
if (str.length == 0)
return obj
var c = str.substr(0,1)
var s = c=='?' || c=='#' ? str.substr(1) : str;
var a = s.split(separator)
for (var i=0; i<a.length; i++) {
var p = a[i].indexOf('=')
if (p < 0) {
obj[a[i]] = ''
continue
}
var k = decodeURIComponent(a[i].substr(0,p)),
v = decodeURIComponent(a[i].substr(p+1))
var bps = k.indexOf('[')
if (bps < 0) {
obj[k] = v
continue;
}
var bpe = k.substr(bps+1).indexOf(']')
if (bpe < 0) {
obj[k] = v
continue;
}
var bpv = k.substr(bps+1, bps+bpe-1)
var k = k.substr(0,bps)
if (bpv.length <= 0) {
if (typeof(obj[k]) != 'object') obj[k] = []
obj[k].push(v)
} else {
if (typeof(obj[k]) != 'object') obj[k] = {}
obj[k][bpv] = v
}
}
return obj;
}
http://someurl.com?key=value&keynovalue&keyemptyvalue=&&keynovalue=nowhasvalue#somehash
常规键/值对(?param=值)不带值的键(?param:无等号或值)键w/空值(?param=:等号,但等号右侧没有值)重复键(?param=1¶m=2)删除空键(?&&:无键或值)
代码:
var queryString=window.location.search | |“”;var keyValPairs=[];var参数={};queryString=queryString.substr(1);if(queryString.length){keyValPairs=queryString.split('&');for(keyValPairs中的pairNum){var key=keyValPairs[pairNum].split('=')[0];如果(!key.length)继续;if(typeof params[key]==“undefined”)params[key]=[];params[key].push(keyValPairs[pairNum].split('=')[1]);}}
如何呼叫:
params['key'];//返回值数组(1..n)
输出:
键[“value”]关键字空值[“”]注释记号[未定义,“nowhasvalue”]