如何使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:49:53  来源:igfitidea点击:

how to get HTTP GET request value using javascript

javascriptget

提问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

回答by Toni Toni Chopper

Build the URL string and use jQuery get

构建 URL 字符串并使用 jQuery get