是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
当前回答
可靠地做这件事比一开始想象的要复杂得多。
其他答案中使用的location.search很脆弱,应该避免使用-例如,如果有人搞砸了,并在?查询字符串。在我看来,URL在浏览器中自动转义的方式有很多种,这使得decodeURIComponent非常强制性。许多查询字符串是由用户输入生成的,这意味着对URL内容的假设非常糟糕。包括非常基本的东西,比如每个键都是唯一的,甚至有一个值。
为了解决这个问题,这里提供了一个可配置的API,并提供了健康的防御性编程。请注意,如果您愿意对某些变量进行硬编码,或者如果输入不能包含hasOwnProperty等,则可以将其大小减半。
版本1:返回包含每个参数的名称和值的数据对象。它有效地消除了重复,并始终尊重从左到右找到的第一个。
function getQueryData(url, paramKey, pairKey, missingValue, decode) {
var query, queryStart, fragStart, pairKeyStart, i, len, name, value, result;
if (!url || typeof url !== 'string') {
url = location.href; // more robust than location.search, which is flaky
}
if (!paramKey || typeof paramKey !== 'string') {
paramKey = '&';
}
if (!pairKey || typeof pairKey !== 'string') {
pairKey = '=';
}
// when you do not explicitly tell the API...
if (arguments.length < 5) {
// it will unescape parameter keys and values by default...
decode = true;
}
queryStart = url.indexOf('?');
if (queryStart >= 0) {
// grab everything after the very first ? question mark...
query = url.substring(queryStart + 1);
} else {
// assume the input is already parameter data...
query = url;
}
// remove fragment identifiers...
fragStart = query.indexOf('#');
if (fragStart >= 0) {
// remove everything after the first # hash mark...
query = query.substring(0, fragStart);
}
// make sure at this point we have enough material to do something useful...
if (query.indexOf(paramKey) >= 0 || query.indexOf(pairKey) >= 0) {
// we no longer need the whole query, so get the parameters...
query = query.split(paramKey);
result = {};
// loop through the parameters...
for (i = 0, len = query.length; i < len; i = i + 1) {
pairKeyStart = query[i].indexOf(pairKey);
if (pairKeyStart >= 0) {
name = query[i].substring(0, pairKeyStart);
} else {
name = query[i];
}
// only continue for non-empty names that we have not seen before...
if (name && !Object.prototype.hasOwnProperty.call(result, name)) {
if (decode) {
// unescape characters with special meaning like ? and #
name = decodeURIComponent(name);
}
if (pairKeyStart >= 0) {
value = query[i].substring(pairKeyStart + 1);
if (value) {
if (decode) {
value = decodeURIComponent(value);
}
} else {
value = missingValue;
}
} else {
value = missingValue;
}
result[name] = value;
}
}
return result;
}
}
版本2:返回一个具有两个相同长度数组的数据映射对象,一个用于名称,另一个用于值,每个参数都有一个索引。此格式支持重复名称,并故意不消除重复名称,因为这可能就是您希望使用此格式的原因。
function getQueryData(url, paramKey, pairKey, missingValue, decode) {
var query, queryStart, fragStart, pairKeyStart, i, len, name, value, result;
if (!url || typeof url !== 'string') {
url = location.href; // more robust than location.search, which is flaky
}
if (!paramKey || typeof paramKey !== 'string') {
paramKey = '&';
}
if (!pairKey || typeof pairKey !== 'string') {
pairKey = '=';
}
// when you do not explicitly tell the API...
if (arguments.length < 5) {
// it will unescape parameter keys and values by default...
decode = true;
}
queryStart = url.indexOf('?');
if (queryStart >= 0) {
// grab everything after the very first ? question mark...
query = url.substring(queryStart + 1);
} else {
// assume the input is already parameter data...
query = url;
}
// remove fragment identifiers...
fragStart = query.indexOf('#');
if (fragStart >= 0) {
// remove everything after the first # hash mark...
query = query.substring(0, fragStart);
}
// make sure at this point we have enough material to do something useful...
if (query.indexOf(paramKey) >= 0 || query.indexOf(pairKey) >= 0) {
// we no longer need the whole query, so get the parameters...
query = query.split(paramKey);
result = {
names: [],
values: []
};
// loop through the parameters...
for (i = 0, len = query.length; i < len; i = i + 1) {
pairKeyStart = query[i].indexOf(pairKey);
if (pairKeyStart >= 0) {
name = query[i].substring(0, pairKeyStart);
} else {
name = query[i];
}
// only continue for non-empty names...
if (name) {
if (decode) {
// unescape characters with special meaning like ? and #
name = decodeURIComponent(name);
}
if (pairKeyStart >= 0) {
value = query[i].substring(pairKeyStart + 1);
if (value) {
if (decode) {
value = decodeURIComponent(value);
}
} else {
value = missingValue;
}
} else {
value = missingValue;
}
result.names.push(name);
result.values.push(value);
}
}
return result;
}
}
其他回答
Use:
$(document).ready(function () {
var urlParams = {};
(function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) {
return decodeURIComponent(s.replace(pl, " "));
},
query = window.location.search.substring(1);
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
if (urlParams["q1"] === 1) {
return 1;
}
请检查并让我知道您的意见。另请参阅How to get querystring value using jQuery。
这个很好用。其他一些答案中的正则表达式引入了不必要的开销。
function getQuerystring(key) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == key) {
return pair[1];
}
}
}
从这里取的
代码高尔夫:
var a = location.search&&location.search.substr(1).replace(/\+/gi," ").split("&");
for (var i in a) {
var s = a[i].split("=");
a[i] = a[unescape(s[0])] = unescape(s[1]);
}
显示它!
for (i in a) {
document.write(i + ":" + a[i] + "<br/>");
};
在我的Mac上:test.htm?i=can&has=cheezburg显示屏
0:can
1:cheezburger
i:can
has:cheezburger
function GET() {
var data = [];
for(x = 0; x < arguments.length; ++x)
data.push(location.href.match(new RegExp("/\?".concat(arguments[x],"=","([^\n&]*)")))[1])
return data;
}
example:
data = GET("id","name","foo");
query string : ?id=3&name=jet&foo=b
returns:
data[0] // 3
data[1] // jet
data[2] // b
or
alert(GET("id")[0]) // return 3
function getUrlVar(key){
var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search);
return result && unescape(result[1]) || "";
}
https://gist.github.com/1771618