是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
当前回答
关于这个问题的顶级答案的问题是,不支持在#后面放置参数,但有时也需要获得这个值。
我修改了答案,让它解析带有哈希符号的完整查询字符串:
var getQueryStringData = function(name) {
var result = null;
var regexS = "[\\?&#]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec('?' + window.location.href.split('?')[1]);
if (results != null) {
result = decodeURIComponent(results[1].replace(/\+/g, " "));
}
return result;
};
其他回答
我使用这里列出的技术开发了一个小型库,以创建一个易于使用的解决方案;可以在这里找到:
https://github.com/Nijikokun/query-js
用法
正在获取特定参数/密钥:
query.get('param');
使用生成器获取整个对象:
var storage = query.build();
console.log(storage.param);
还有很多。。。查看github链接以获取更多示例。
特征
解码和参数缓存支持哈希查询字符串#hello?第3页支持传递自定义查询支持数组/对象参数user[]=“jim”&user[]=”bob“支持空管理&&支持不带值的声明参数name&hello=“world”支持重复参数param=1¶m=2干净、紧凑、可读的源4kbAMD,需要,节点支持
以下是我正在使用的:
/**
* Examples:
* getUrlParams()['myparam'] // url defaults to the current page
* getUrlParams(url)['myparam'] // url can be just a query string
*
* Results of calling `getUrlParams(url)['myparam']` with various urls:
* example.com (undefined)
* example.com? (undefined)
* example.com?myparam (empty string)
* example.com?myparam= (empty string)
* example.com?myparam=0 (the string '0')
* example.com?myparam=0&myparam=override (the string 'override')
*
* Origin: http://stackoverflow.com/a/23946023/2407309
*/
function getUrlParams (url) {
var urlParams = {} // return value
var queryString = getQueryString()
if (queryString) {
var keyValuePairs = queryString.split('&')
for (var i = 0; i < keyValuePairs.length; i++) {
var keyValuePair = keyValuePairs[i].split('=')
var paramName = keyValuePair[0]
var paramValue = keyValuePair[1] || ''
urlParams[paramName] = decodeURIComponent(paramValue.replace(/\+/g, ' '))
}
}
return urlParams // functions below
function getQueryString () {
var reducedUrl = url || window.location.search
reducedUrl = reducedUrl.split('#')[0] // Discard fragment identifier.
var queryString = reducedUrl.split('?')[1]
if (!queryString) {
if (reducedUrl.search('=') !== false) { // URL is a query string.
queryString = reducedUrl
}
}
return queryString
} // getQueryString
} // getUrlParams
在最后一种情况下,返回“override”而不是“0”使其与PHP一致。在IE7中工作。
从MDN:
function loadPageVar (sVar) {
return unescape(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}
alert(loadPageVar("name"));
这是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;
};
我在这里做了一个小的URL库来满足我的需求:https://github.com/Mikhus/jsurl
这是一种在JavaScript中操纵URL的更常见的方法。同时,它非常轻量级(缩小和gzip<1KB),并且具有非常简单和干净的API。而且它不需要任何其他库来工作。
关于最初的问题,很简单:
var u = new Url; // Current document URL
// or
var u = new Url('http://user:pass@example.com:8080/some/path?foo=bar&bar=baz#anchor');
// Looking for query string parameters
alert( u.query.bar);
alert( u.query.foo);
// Modifying query string parameters
u.query.foo = 'bla';
u.query.woo = ['hi', 'hey']
alert(u.query.foo);
alert(u.query.woo);
alert(u);