如何从 JavaScript 检索 GET 参数 [英] How to retrieve GET parameters from JavaScript
问题描述
考虑:
http://example.com/page.html?returnurl=%2Fadmin
对于page.html
中的js
,如何获取GET
参数?
For js
within page.html
, how can it retrieve GET
parameters?
对于上面的简单例子,func('returnurl')
应该是 /admin
.
For the above simple example, func('returnurl')
should be /admin
.
但它也应该适用于复杂的查询字符串...
But it should also work for complex query strings...
推荐答案
使用 window.位置 对象.此代码为您提供不带问号的 GET.
With the window.location object. This code gives you GET without the question mark.
window.location.search.substr(1)
从您的示例中,它将返回 returnurl=%2Fadmin
From your example it will return returnurl=%2Fadmin
编辑:我冒昧地更改了Qwerty 的答案,这是非常好,正如他指出的那样,我完全按照 OP 的要求进行操作:
EDIT: I took the liberty of changing Qwerty's answer, which is really good, and as he pointed I followed exactly what the OP asked:
function findGetParameter(parameterName) {
var result = null,
tmp = [];
location.search
.substr(1)
.split("&")
.forEach(function (item) {
tmp = item.split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
});
return result;
}
我从他的代码中删除了重复的函数执行,将其替换为一个变量( tmp ),并且我还添加了 decodeURIComponent
,正如 OP 所要求的那样.我不确定这是否是安全问题.
I removed the duplicated function execution from his code, replacing it a variable ( tmp ) and also I've added decodeURIComponent
, exactly as OP asked. I'm not sure if this may or may not be a security issue.
或者使用普通的 for 循环,即使在 IE8 中也能工作:
Or otherwise with plain for loop, which will work even in IE8:
function findGetParameter(parameterName) {
var result = null,
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
}
return result;
}
这篇关于如何从 JavaScript 检索 GET 参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!