是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
当前回答
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。
其他回答
这是我对这个优秀答案的编辑——增加了解析带有键而没有值的查询字符串的能力。
var url = 'http://sb.com/reg/step1?param';
var qs = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i) {
var p=a[i].split('=', 2);
if (p[1]) p[1] = decodeURIComponent(p[1].replace(/\+/g, " "));
b[p[0]] = p[1];
}
return b;
})((url.split('?'))[1].split('&'));
重要!最后一行中该函数的参数不同。这只是一个如何向其传递任意URL的示例。您可以使用Bruno答案的最后一行来解析当前URL。
那么到底发生了什么变化?使用urlhttp://sb.com/reg/step1?param=结果是一样的。但使用urlhttp://sb.com/reg/step1?paramBruno的解决方案返回一个没有键的对象,而我的解决方案则返回一个带有键参数和未定义值的对象。
ES2015(ES6)
getQueryStringParams = query => {
return query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split('&')
.reduce((params, param) => {
let [key, value] = param.split('=');
params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
return params;
}, {}
)
: {}
};
没有jQuery
var qs = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=', 2);
if (p.length == 1)
b[p[0]] = "";
else
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'));
URL如下?topic=123&name=query+string,将返回以下内容:
qs["topic"]; // 123
qs["name"]; // query string
qs["nothere"]; // undefined (object)
Google方法
撕扯谷歌的代码,我找到了他们使用的方法:getUrlParameters
function (b) {
var c = typeof b === "undefined";
if (a !== h && c) return a;
for (var d = {}, b = b || k[B][vb], e = b[p]("?"), f = b[p]("#"), b = (f === -1 ? b[Ya](e + 1) : [b[Ya](e + 1, f - e - 1), "&", b[Ya](f + 1)][K](""))[z]("&"), e = i.dd ? ia : unescape, f = 0, g = b[w]; f < g; ++f) {
var l = b[f][p]("=");
if (l !== -1) {
var q = b[f][I](0, l),
l = b[f][I](l + 1),
l = l[Ca](/\+/g, " ");
try {
d[q] = e(l)
} catch (A) {}
}
}
c && (a = d);
return d
}
这是模糊的,但可以理解。它无法工作,因为某些变量未定义。
他们开始在url上查找参数?并且还从散列#中。然后,对于每个参数,它们以等号b[f][p](“=”)分割(看起来像indexOf,它们使用字符的位置来获取键/值)。拆分后,他们检查参数是否有值,如果有值,则存储d的值,否则继续。
最后返回对象d,处理转义和+符号。这个对象和我的一样,它有相同的行为。
我的方法作为jQuery插件
(function($) {
$.QueryString = (function(paramsArray) {
let params = {};
for (let i = 0; i < paramsArray.length; ++i)
{
let param = paramsArray[i]
.split('=', 2);
if (param.length !== 2)
continue;
params[param[0]] = decodeURIComponent(param[1].replace(/\+/g, " "));
}
return params;
})(window.location.search.substr(1).split('&'))
})(jQuery);
用法
//Get a param
$.QueryString.param
//-or-
$.QueryString["param"]
//This outputs something like...
//"val"
//Get all params as object
$.QueryString
//This outputs something like...
//Object { param: "val", param2: "val" }
//Set a param (only in the $.QueryString object, doesn't affect the browser's querystring)
$.QueryString.param = "newvalue"
//This doesn't output anything, it just updates the $.QueryString object
//Convert object into string suitable for url a querystring (Requires jQuery)
$.param($.QueryString)
//This outputs something like...
//"param=newvalue¶m2=val"
//Update the url/querystring in the browser's location bar with the $.QueryString object
history.replaceState({}, '', "?" + $.param($.QueryString));
//-or-
history.pushState({}, '', "?" + $.param($.QueryString));
性能测试(针对正则表达式方法的拆分方法)(jsPerf)
准备代码:方法声明
拆分测试代码
var qs = window.GetQueryString(query);
var search = qs["q"];
var value = qs["value"];
var undef = qs["undefinedstring"];
Regex测试代码
var search = window.getParameterByName("q");
var value = window.getParameterByName("value");
var undef = window.getParameterByName("undefinedstring");
在Windows Server 2008 R2/7 x64上的Firefox 4.0 x86中测试
拆分方法:最快144780±2.17%Regex方法:13891±0.85%|90%慢
非常轻量级的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)
我接受了这个答案,并添加了对可选地将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);
下面是我将Andy E的优秀解决方案打造成一个成熟的jQuery插件的尝试:
;(function ($) {
$.extend({
getQueryString: function (name) {
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[name];
}
});
})(jQuery);
语法为:
var someVar = $.getQueryString('myParam');
两全其美!