【问题标题】:how to get HTTP GET request value using javascript [duplicate]如何使用javascript获取HTTP GET请求值[重复]
【发布时间】:2012-11-25 08:32:15
【问题描述】:

可能重复:
How can I get query string values?

如何使用 javascript 获取 HTTP GET 请求?

例如,如果我可以访问www.sample.com/div/a/dev.php?name=sample

如何获取name=sample 的GET 请求以及name 的值sample

【问题讨论】:

标签: javascript get


【解决方案1】:

您可以使用 location.href 获取完整的 URL,然后使用 split 提取值

【讨论】:

    【解决方案2】:

    构建 URL 字符串并使用 jQuery get

    【讨论】:

      【解决方案3】:

      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"] 
      

      【讨论】:

      • 将返回一个包含所有查询字符串参数、锚点和问号后面的任何内容的字符串。
      • 可以从'='中拆分字符串,得到参数和值
      • 你测试过这个吗? parameter = "foo=bar&blah=123",结果["foo", "bar&blah", "123"]
      【解决方案4】:
      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"
      }
      

      【讨论】:

        猜你喜欢
        • 2021-09-12
        • 2021-08-04
        • 1970-01-01
        • 2019-11-24
        • 1970-01-01
        • 2017-12-31
        • 1970-01-01
        • 2018-08-10
        • 1970-01-01
        相关资源
        最近更新 更多