是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?
如果是,怎么办?如果没有,是否有插件可以这样做?
当前回答
查看此帖子或使用此:
<script type="text/javascript" language="javascript">
$(document).ready(function()
{
var urlParams = {};
(function ()
{
var match,
pl= /\+/g, // Regular expression 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;
}
});
</script>
其他回答
这里发布的一些解决方案效率低下。每次脚本需要访问参数时重复正则表达式搜索是完全不必要的,一个函数将参数拆分为关联数组样式对象就足够了。如果您不使用HTML5历史API,则每次加载页面只需要一次。这里的其他建议也无法正确解码URL。
var urlParams;
(window.onpopstate = 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);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
示例查询字符串:
?i=main&mode=front&sid=de8d49b78a85a322c4155015fdce22c4&enc=+Hello%20&empty
结果:
urlParams = {
enc: " Hello ",
i: "main",
mode: "front",
sid: "de8d49b78a85a322c4155015fdce22c4",
empty: ""
}
alert(urlParams["mode"]);
// -> "front"
alert("empty" in urlParams);
// -> true
这也可以很容易地改进为处理数组样式的查询字符串。这里有一个这样的例子,但由于RFC 3986中没有定义数组样式参数,所以我不会用源代码污染这个答案。对于那些对“污染”版本感兴趣的人,请看下面坎贝尔的答案。
此外,正如评论中指出的;是key=value对的合法分隔符。它需要更复杂的正则表达式来处理;或&,我认为这是不必要的,因为这很少见;我想说,更不可能两者都使用。如果您需要支持;而不是&,只是在正则表达式中交换它们。
<script>var urlParams = <?php echo json_encode($_GET, JSON_HEX_TAG);?>;</script>
简单多了!
#已更新
一个新的功能是检索重复的参数,如下myparam=1和myparam=2。然而,没有一个规范,目前的大多数方法都遵循数组的生成。
myparam = ["1", "2"]
因此,这是管理它的方法:
let urlParams = {};
(window.onpopstate = function () {
let 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)) {
if (decode(match[1]) in urlParams) {
if (!Array.isArray(urlParams[decode(match[1])])) {
urlParams[decode(match[1])] = [urlParams[decode(match[1])]];
}
urlParams[decode(match[1])].push(decode(match[2]));
} else {
urlParams[decode(match[1])] = decode(match[2]);
}
}
})();
这会奏效的。。。您需要在需要通过传递其名称来获取参数的地方调用此函数。。。
function getParameterByName(name)
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
alert(results[1]);
if (results == null)
return "";
else
return results[1];
}
更新: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”的答案。
试试看:
String.prototype.getValueByKey = function(k){
var p = new RegExp('\\b'+k+'\\b','gi');
return this.search(p) != -1 ? decodeURIComponent(this.substr(this.search(p)+k.length+1).substr(0,this.substr(this.search(p)+k.length+1).search(/(&|;|$)/))) : "";
};
然后这样称呼:
if(location.search != "") location.search.getValueByKey("id");
您还可以将此用于cookie:
if(navigator.cookieEnabled) document.cookie.getValueByKey("username");
这只适用于key=value[&|;|$]。。。将无法处理对象/数组。
如果您不想使用String.prototype。。。将其移动到函数并将字符串作为参数传递
这是我自己的看法。第一个函数将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;
};