如何使用 javascript 获取 HTTP GET 请求值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13758417/
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 get HTTP GET request value using javascript
提问by gadss
Possible Duplicate:
How can I get query string values?
可能重复:
如何获取查询字符串值?
how can I get the HTTP GET request using javascript?
如何使用 javascript 获取 HTTP GET 请求?
for example if I have access www.sample.com/div/a/dev.php?name=sample
例如,如果我有访问权限 www.sample.com/div/a/dev.php?name=sample
how can I get the GET request of name=sampleand the value if namewhich is sample?
我怎样才能得到 GET 请求name=sample和值(如果name是)sample?
采纳答案by Viren Rajput
The window.locationobject might come useful here:
该window.location的对象可能来这里很有用:
var parameter = window.location.search.replace( "?", "" ); // will return the GET parameter
var values = parameter.split("=");
console.log(values); // will return and array as ["name", "sample"]
回答by vaibhav
Here is a fast way to get an object similar to the PHP $_GET array:
function get_query(){
var url = location.href;
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = qs[i][1];
}
return result;
}
Usage:
var $_GET = get_query();
For the query string x=5&y&z=hello&x=6 this returns the object:
{
x: "6",
y: undefined,
z: "hello"
}
回答by Matanya
You can use location.hrefto fetch the full URL and then extract the values using split
您可以使用location.href获取完整的 URL,然后使用提取值split

![摆脱 Visual Studio 中的 [动态] JavaScript 视图](/res/img/loading.gif)