是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
当前回答
更新:2022年1月
使用Proxy()比使用Object.fromEntries()更快,并且更受支持
const params = new Proxy(new URLSearchParams(window.location.search), {
get: (searchParams, prop) => searchParams.get(prop),
});
// Get the value of "some_key" in eg "https://example.com/?some_key=some_value"
let value = params.some_key; // "some_value"
更新日期:2021年6月
对于需要所有查询参数的特定情况:
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
更新:2018年9月
您可以使用URLSearchParams,它很简单,并且具有良好(但不完全)的浏览器支持。
const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get('myParam');
起初的
为此,您不需要jQuery。您可以使用一些纯JavaScript:
function getParameterByName(name, url = window.location.href) {
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
用法:
// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
var bar = getParameterByName('bar'); // "" (present with empty value)
var baz = getParameterByName('baz'); // "" (present with no value)
var qux = getParameterByName('qux'); // null (absent)
注意:如果参数出现多次(?foo=lorem&foo=ipsum),您将获得第一个值(lorem)。关于这一点没有标准,用法也各不相同,请参见例如这个问题:重复HTTPGET查询键的权威位置。
注意:该函数区分大小写。如果您喜欢不区分大小写的参数名,请在RegExp中添加“i”修饰符
注意:如果您得到了一个无无用转义esint错误,可以替换name=name.replace(/[\[\]]/g,'\\$&');其中name=name。replace(/[[\]]/g,'\\$&')。
这是基于新URLSearchParams规范的更新,以更简洁地实现相同的结果。请参阅下面标题为“URLSearchParams”的答案。
其他回答
我需要查询字符串中的一个对象,我讨厌很多代码。它可能不是世界上最健壮的,但它只是几行代码。
var q = {};
location.href.split('?')[1].split('&').forEach(function(i){
q[i.split('=')[0]]=i.split('=')[1];
});
像这样的URL.htm?hello=world&foo=bar将创建:
{hello:'world', foo:'bar'}
Roshambo jQuery方法没有处理解码URL
http://snipplr.com/view/26662/get-url-parameters-with-jquery--improved/
在return语句中添加时也添加了该功能
return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;
现在您可以找到更新的要点:
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return 0; }
return decodeURIComponent(results[1].replace(/\+/g, " ")) || 0;
}
这是我自己的看法。第一个函数将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;
};
如果您使用的是jQuery,那么可以使用一个库,例如jQueryBBQ:返回按钮和查询库。
…jQueryBBQ提供了一个完整的.depam()方法,以及哈希状态管理、片段/查询字符串解析和合并实用程序方法。
编辑:添加参数示例:
var DeparamExample=函数(){var params=$.depam.querystring();//nameofram是来自url的参数的名称//如果ajax使用哈希刷新,下面的代码将获取参数if(typeof params.nameofram==“undefined”){params=jQuery.departam.frage(window.location.href);}if(typeof params.nameofram!=“undefined”){var paramValue=params.nameofram.toString();}};
如果您只想使用纯JavaScript,可以使用。。。
var getParamValue = (function() {
var params;
var resetParams = function() {
var query = window.location.search;
var regex = /[?&;](.+?)=([^&;]+)/g;
var match;
params = {};
if (query) {
while (match = regex.exec(query)) {
params[match[1]] = decodeURIComponent(match[2]);
}
}
};
window.addEventListener
&& window.addEventListener('popstate', resetParams);
resetParams();
return function(param) {
return params.hasOwnProperty(param) ? params[param] : null;
}
})();
由于新的HTML历史API,特别是History.pushState()和History.replaceState(),URL可能会发生更改,这将使参数及其值的缓存无效。
此版本将在每次更改历史记录时更新其内部参数缓存。
我宁愿使用split()而不是Regex执行此操作:
function getUrlParams() {
var result = {};
var params = (window.location.search.split('?')[1] || '').split('&');
for(var param in params) {
if (params.hasOwnProperty(param)) {
var paramParts = params[param].split('=');
result[paramParts[0]] = decodeURIComponent(paramParts[1] || "");
}
}
return result;
}