是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
当前回答
function GetQueryStringParams(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
假设URL为
http://example.com/?stringtext=jquery&stringword=jquerybyexample
var tech = GetQueryStringParams('stringtext');
var blog = GetQueryStringParams('stringword');
其他回答
如果您使用的是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可能会发生更改,这将使参数及其值的缓存无效。
此版本将在每次更改历史记录时更新其内部参数缓存。
更新: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”的答案。
function getUrlVar(key){
var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search);
return result && unescape(result[1]) || "";
}
https://gist.github.com/1771618
下面是我将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');
两全其美!
只是另一个建议。插件Purl允许检索URL的所有部分,包括锚点、主机等。
它可以与jQuery一起使用,也可以不使用jQuery。
用法很简单,很酷:
var url = $.url('http://example.com/folder/dir/index.html?item=value'); // jQuery version
var url = purl('http://example.com/folder/dir/index.html?item=value'); // plain JS version
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'
然而,截至2014年11月11日,Purl不再被维护,作者建议改用URI.js。jQuery插件的不同之处在于它关注元素-对于字符串使用,只需直接使用URI,无论是否使用jQuery。类似的代码看起来是这样的,更完整的文档如下:
var url = new URI('http://example.com/folder/dir/index.html?item=value'); // plain JS version
url.protocol(); // returns 'http'
url.path(); // returns '/folder/dir/index.html'