是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
当前回答
这将从URL字符串中解析变量AND数组。它既不使用正则表达式,也不使用任何外部库。
function url2json(url) {
var obj={};
function arr_vals(arr){
if (arr.indexOf(',') > 1){
var vals = arr.slice(1, -1).split(',');
var arr = [];
for (var i = 0; i < vals.length; i++)
arr[i]=vals[i];
return arr;
}
else
return arr.slice(1, -1);
}
function eval_var(avar){
if (!avar[1])
obj[avar[0]] = '';
else
if (avar[1].indexOf('[') == 0)
obj[avar[0]] = arr_vals(avar[1]);
else
obj[avar[0]] = avar[1];
}
if (url.indexOf('?') > -1){
var params = url.split('?')[1];
if(params.indexOf('&') > 2){
var vars = params.split('&');
for (var i in vars)
eval_var(vars[i].split('='));
}
else
eval_var(params.split('='));
}
return obj;
}
例子:
var url = "http://www.x.com?luckyNums=[31,21,6]&name=John&favFoods=[pizza]&noVal"
console.log(url2json(url));
输出:
[object]
noVal: ""
favFoods: "pizza"
name: "John"
luckyNums:
0: "31"
1: "21"
2: "6"
其他回答
如果您要做的URL操作比简单地解析查询字符串更多,那么您可能会发现URI.js很有用。它是一个用于操作URL的库,并且附带了所有的提示。(很抱歉在这里自我宣传)
要将查询字符串转换为映射,请执行以下操作:
var data = URI('?foo=bar&bar=baz&foo=world').query(true);
data == {
"foo": ["bar", "world"],
"bar": "baz"
}
(URI.js还“修复”了错误的查询字符串,如?&foo&&bar=baz&to?foo&bar=baz)
非常轻量级的jQuery方法:
var qs = window.location.search.replace('?','').split('&'),
request = {};
$.each(qs, function(i,v) {
var initial, pair = v.split('=');
if(initial = request[pair[0]]){
if(!$.isArray(initial)) {
request[pair[0]] = [initial]
}
request[pair[0]].push(pair[1]);
} else {
request[pair[0]] = pair[1];
}
return;
});
console.log(request);
例如,提醒?q
alert(request.q)
可靠地做这件事比一开始想象的要复杂得多。
其他答案中使用的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;
}
}
这里有一个很好的小url实用程序,带有一些很酷的糖霜:
http://www.example.com/path/index.html?silly=willy#chucky=cheese
url(); // http://www.example.com/path/index.html?silly=willy#chucky=cheese
url('domain'); // example.com
url('1'); // path
url('-1'); // index.html
url('?'); // silly=willy
url('?silly'); // willy
url('?poo'); // (an empty string)
url('#'); // chucky=cheese
url('#chucky'); // cheese
url('#poo'); // (an empty string)
查看更多示例并在此处下载:https://github.com/websanova/js-url#url
Node.js的源代码中有一个健壮的实现https://github.com/joyent/node/blob/master/lib/querystring.js
TJ的qs也执行嵌套参数解析https://github.com/visionmedia/node-querystring