是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
当前回答
URL搜索参数
Firefox 44+、Opera 36+、Edge 17+、Safari 10.3+和Chrome 49+支持URLSearchParams API:
Chrome公告和详细信息歌剧院公告和详情Firefox公告和详细信息
谷歌建议URLSearchParams polyfill用于IE的稳定版本。
它没有被W3C标准化,但它是WhatWG的生活标准。
您可以在以下位置使用它:
const params = new URLSearchParams(location.search);
or
const params = (new URL(location)).searchParams;
当然也可以在任何URL上:
const url = new URL('https://example.com?foo=1&bar=2');
const params = new URLSearchParams(url.search);
还可以使用URL对象上的速记.searchParams属性获取参数,如下所示:
const params = new URL('https://example.com?foo=1&bar=2').searchParams;
params.get('foo'); // "1"
params.get('bar'); // "2"
通过get(KEY)、set(KEY,VALUE)、append(KEY,VAL)API读取/设置参数。您还可以遍历(let p of params){}的所有值。
参考实现和示例页面可用于审计和测试。
其他回答
下面是一种快速获取类似于PHP$_get数组的对象的方法:
function get_query(){
var url = location.search;
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][1]);
}
return result;
}
用法:
var $_GET = get_query();
对于查询字符串x=5&y&z=hello&x=6,这将返回对象:
{
x: "6",
y: undefined,
z: "hello"
}
下面是我将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');
两全其美!
我认为这是实现这一点的准确和简洁的方法(修改自http://css-tricks.com/snippets/javascript/get-url-variables/):
function getQueryVariable(variable) {
var query = window.location.search.substring(1), // Remove the ? from the query string.
vars = query.split("&"); // Split all values by ampersand.
for (var i = 0; i < vars.length; i++) { // Loop through them...
var pair = vars[i].split("="); // Split the name from the value.
if (pair[0] == variable) { // Once the requested value is found...
return ( pair[1] == undefined ) ? null : pair[1]; // Return null if there is no value (no equals sign), otherwise return the value.
}
}
return undefined; // Wasn't found.
}
Artem Barger回答的改进版本:
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
有关改进的更多信息,请参阅:http://james.padolsey.com/javascript/bujs-1-getparameterbyname/
这是我自己的看法。第一个函数将URL字符串解码为名称/值对的对象:
url_args_decode = function (url) {
var args_enc, el, i, nameval, ret;
ret = {};
// use the DOM to parse the URL via an 'a' element
el = document.createElement("a");
el.href = url;
// strip off initial ? on search and split
args_enc = el.search.substring(1).split('&');
for (i = 0; i < args_enc.length; i++) {
// convert + into space, split on =, and then decode
args_enc[i].replace(/\+/g, ' ');
nameval = args_enc[i].split('=', 2);
ret[decodeURIComponent(nameval[0])]=decodeURIComponent(nameval[1]);
}
return ret;
};
另外,如果您更改了一些参数,可以使用第二个函数将参数数组放回URL字符串中:
url_args_replace = function (url, args) {
var args_enc, el, name;
// use the DOM to parse the URL via an 'a' element
el = document.createElement("a");
el.href = url;
args_enc = [];
// encode args to go into url
for (name in args) {
if (args.hasOwnProperty(name)) {
name = encodeURIComponent(name);
args[name] = encodeURIComponent(args[name]);
args_enc.push(name + '=' + args[name]);
}
}
if (args_enc.length > 0) {
el.search = '?' + args_enc.join('&');
} else {
el.search = '';
}
return el.href;
};