Javascript 如何从javascript检索GET参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5448545/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to retrieve GET parameters from javascript?
提问by compile-fan
http://domain.com/page.html?returnurl=%2Fadmin
For js
within page.html
,how can it retrieve GET
parameters?
对于js
inside page.html
,它如何检索GET
参数?
For the above simple example,func('returnurl')
should be /admin
对于上面的简单例子,func('returnurl')
应该是/admin
But it should also work for complex querystrngs...
但它也应该适用于复杂的查询字符串...
回答by Bakudan
With the window.locationobject. This code gives you GET without the question mark.
使用window.location对象。此代码为您提供不带问号的 GET。
window.location.search.substr(1)
From your example it will return returnurl=%2Fadmin
从您的示例中,它将返回 returnurl=%2Fadmin
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:
编辑:我冒昧地更改了Qwerty 的答案,这真的很好,正如他指出的那样,我完全按照 OP 的要求进行了操作:
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;
}
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.
我从他的代码中删除了重复的函数执行,将其替换为一个变量( tmp ),并且我还添加了decodeURIComponent
,完全按照 OP 的要求。我不确定这是否可能是安全问题。
Or otherwise with plain for loop, which will work even in IE8:
或者使用普通的 for 循环,即使在 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;
}
回答by weltraumpirat
window.location.search
will return everything from the ? on. This code below will remove the ?, use split to separate into key/value arrays, then assign named properties to the params object:
window.location.search
将返回所有内容?在。下面的代码将删除 ?,使用 split 分隔成键/值数组,然后将命名属性分配给 params 对象:
function getSearchParameters() {
var prmstr = window.location.search.substr(1);
return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}
function transformToAssocArray( prmstr ) {
var params = {};
var prmarr = prmstr.split("&");
for ( var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
var params = getSearchParameters();
You can then get the test parameter from http://myurl.com/?test=1
by calling params.test
.
然后,您可以http://myurl.com/?test=1
通过调用从中获取测试参数params.test
。
回答by Qwerty
tl;drsolution on a single line of code using vanilla javascript
tl;dr使用 vanilla javascript 在一行代码上的解决方案
var queryDict = {}
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
This is the simplest solution. It unfortunately does nothandle multi-valued keys and encoded characters.
这是最简单的解决方案。不幸的是,它不处理多值键和编码字符。
"?a=1&a=%2Fadmin&b=2&c=3&d&e"
> queryDict
a: "%2Fadmin" //overriden with last value, not decoded.
b: "2"
c: "3"
d: undefined
e: undefined
multi-valued keysand encoded characters?
多值键和编码字符?
See the original answer at How can I get query string values in JavaScript?
请参阅如何在 JavaScript 中获取查询字符串值的原始答案?
"?a=1&b=2&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst?le%26car%3Dsaab&a=%2Fadmin"
> queryDict
a: ["1", "5", "t e x t", "/admin"]
b: ["2"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=st?le&car=saab"]
在您的示例中,您将像这样访问值:
"?returnurl=%2Fadmin"
> qd.returnurl // ["/admin"]
> qd['returnurl'] // ["/admin"]
> qd.returnurl[0] // "/admin"
回答by AKnox
You should use URL and URLSearchParams native functions:
您应该使用 URL 和 URLSearchParams 本机函数:
let url = new URL("https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8&q=mdn%20query%20string")
let params = new URLSearchParams(url.search);
let sourceid = params.get('sourceid') // 'chrome-instant'
let q = params.get('q') // 'mdn query string'
let ie = params.has('ie') // true
params.append('ping','pong')
console.log(sourceid)
console.log(q)
console.log(ie)
console.log(params.toString())
console.log(params.get("ping"))
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParamshttps://polyfill.io/v2/docs/features/
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams https://polyfill.io/v2/docs/features/
回答by Stefan
a more fancy way to do it: :)
一种更奇特的方式来做到这一点:)
var options = window.location.search.slice(1)
.split('&')
.reduce(function _reduce (/*Object*/ a, /*String*/ b) {
b = b.split('=');
a[b[0]] = decodeURIComponent(b[1]);
return a;
}, {});
回答by lsblsb
i do it like this (to retrieve a specific get-parameter, here 'parameterName'):
我这样做(要检索特定的获取参数,此处为“参数名称”):
var parameterValue = decodeURIComponent(window.location.search.match(/(\?|&)parameterName\=([^&]*)/)[2]);
回答by Ali
This one use regex and return null if param doesn't exist or has no value:
如果 param 不存在或没有值,则使用正则表达式并返回 null:
function getQuery(q) {
return (window.location.search.match(new RegExp('[?&]' + q + '=([^&]+)')) || [, null])[1];
}
回答by Lucas Serena
Here i've made this code to transform the GET parameters into an object to use them more easily.
在这里,我制作了这段代码来将 GET 参数转换为一个对象,以便更轻松地使用它们。
//Get Nav Url
function getNavUrl() {
//Get Url
return window.location.search.replace("?", "");
};
function getParameters(url) {
//Params obj
var params = {};
//To lowercase
url = url.toLowerCase();
//To array
url = url.split('&');
//Iterate over url parameters array
var length = url.length;
for(var i=0; i<length; i++) {
//Create prop
var prop = url[i].slice(0, url[i].search('='));
//Create Val
var value = url[i].slice(url[i].search('=')).replace('=', '');
//Params New Attr
params[prop] = value;
}
return params;
};
//Call To getParameters
console.log(getParameters(getNavUrl()));
回答by Jonas Sciangula Street
var getQueryParam = function(param) {
var found;
window.location.search.substr(1).split("&").forEach(function(item) {
if (param == item.split("=")[0]) {
found = item.split("=")[1];
}
});
return found;
};
回答by Jonah
This solution handles URL decoding:
此解决方案处理 URL 解码:
var params = function() {
function urldecode(str) {
return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}
function transformToAssocArray( prmstr ) {
var params = {};
var prmarr = prmstr.split("&");
for ( var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = urldecode(tmparr[1]);
}
return params;
}
var prmstr = window.location.search.substr(1);
return prmstr != null && prmstr != "" ? transformToAssocArray(prmstr) : {};
}();
Usage:
用法:
console.log('someParam GET value is', params['someParam']);