【问题标题】:How to retrieve GET parameters from JavaScript [duplicate]如何从 JavaScript 中检索 GET 参数
【发布时间】:2011-07-23 20:13:07
【问题描述】:

考虑:

http://example.com/page.html?returnurl=%2Fadmin

对于page.html内的js,如何获取GET参数?

对于上面的简单示例,func('returnurl') 应该是/admin

但它也应该适用于复杂的查询字符串...

【问题讨论】:

标签: javascript get


【解决方案1】:

使用window.location 对象。此代码为您提供不带问号的 GET。

window.location.search.substr(1)

根据您的示例,它将返回 returnurl=%2Fadmin

编辑:我冒昧地更改了Qwerty's answer,这非常好,正如他指出的那样,我完全按照 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;
}

我从他的代码中删除了重复的函数执行,将其替换为变量 ( tmp ),并且我添加了 decodeURIComponent,完全按照 OP 的要求。我不确定这是否是安全问题。

或者使用普通的 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;
}

【讨论】:

  • 它也应该适用于复杂的查询字符串...
  • 无论大小,它都会返回所有的get查询,但它会是一个很长的字符串。
  • 这个答案在问题定义和实现上都是完全错误的。因此,如果您无论如何要返回整个查询字符串,这不是提问者所要求的,您至少应该使用location.search.substr(1)
  • 我喜欢。我也喜欢简单的for 版本。改变了我的反对意见。无论如何,我之所以建议substrsubstringslice (1) 是因为有不必要的阅读和搜索任务?在replace().
  • @Qwerty 我改成子字符串-查询字符串中可能有一个问号(甚至转义- %3F)
【解决方案2】:

您可以使用 location 对象中提供的 search 功能。搜索功能给出了 URL 的参数部分。详情请见Location Object

您必须解析结果字符串以获取变量及其值,例如在 '=' 上拆分它们。

【讨论】:

    【解决方案3】:

    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();
    

    然后您可以通过调用params.testhttp://myurl.com/?test=1 获取test 参数。

    【讨论】:

    • @Bakudan for...in 是您处理对象的时候。对于数组,最好使用 for 循环,请参阅 this question on for...in with arrays
    • 伤害不大,但重点。由于此处解释的原因:programmers.stackexchange.com/a/120362,不过,我不会返回 null,而是返回空的 {} 对象。
    • 也许你应该把它变成一个函数并插入: if (prmstr == "") { return null; } 在第 2 行。否则,如果没有“?”在 URL 中,您最终将“参数”设置为 Object {: undefined},这很奇怪。
    • @weltraumpirat,我实际上正在编辑我的评论以建议返回 {},但我没有看到您的回复。无论如何感谢您更新您的代码:)
    • 我已经修改了您的精彩代码,以允许像 ?q=abc&amp;g[]=1&amp;g[]=2 这样的情况成为具有 2 个参数的关联数组:q & g 其中 g 是具有 2 个值的数组。 gist.github.com/simkimsia/11372570
    【解决方案4】:

    一个更奇特的方式来做到这一点::)

    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;
                          }, {});
    

    【讨论】:

    • 确实很漂亮,但要注意 reduce 并不兼容所有浏览器。更多信息在这里:stackoverflow.com/questions/7094935/ie-js-reduce-on-an-object
    • 值得注意的是它在 IE8 中不受支持
    • 如果有url作为参数,decodeURIComponent会误将其解析为另一个&key=val对。
    • 正如 Qwerty 指出的那样:应该将 decodeURIComponent 移到里面:a[b[0]] = decodeURIComponent(b[1])
    【解决方案5】:

    tl;dr 使用 vanilla JavaScript 的单行代码解决方案

    var queryDict = {}
    location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
    

    这是最简单的解决方案。不幸的是,它处理多值键和编码字符。

    "?a=1&a=%2Fadmin&b=2&c=3&d&e"
    > queryDict
    a: "%2Fadmin"  // Overridden with the last value, not decoded.
    b: "2"
    c: "3"
    d: undefined
    e: undefined
    

    多值键编码字符

    How can I get query string values in 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"
    

    【讨论】:

    • 似乎是这里的最佳答案。
    • 感谢您注意到我的错误。我还冒昧地修改了您的代码,删除了第二个拆分调用,可以用局部变量替换。
    • 简短易懂:)
    • 什么是香草?另一个js注入? @NaveedHasan
    • @NaveedHasan VanillaJS 是一个源自纯 javascript 的笑话名称的术语,没有额外的库。 See here.
    【解决方案6】:

    我的解决方案在 @tak3r 的基础上进行了扩展。

    没有查询参数时返回空对象,支持数组表示法?a=1&amp;a=2&amp;a=3

    function getQueryParams () {
      function identity (e) { return e; }
      function toKeyValue (params, param) {
        var keyValue = param.split('=');
        var key = keyValue[0], value = keyValue[1];
    
        params[key] = params[key]?[value].concat(params[key]):value;
        return params;
      }
      return decodeURIComponent(window.location.search).
        replace(/^\?/, '').split('&').
        filter(identity).
        reduce(toKeyValue, {});
    }
    

    【讨论】:

    • 目前没有用户名“tak3r”的任何答案或评论(用户名可以随时更改)。它指的是什么?
    【解决方案7】:

    我这样做(检索特定的 get-parameter,这里是 'parameterName'):

    var parameterValue = decodeURIComponent(window.location.search.match(/(\?|&)parameterName\=([^&]*)/)[2]);
    

    【讨论】:

    • 这很好很简短。我也更喜欢在我的代码中这样做。
    • 这很好用,但在省略参数时会产生错误...您可以通过将匹配项存储在变量中并检查它是否等于 null 来修复它,但这会破坏单线性质:/
    【解决方案8】:

    如果您不介意使用库而不是滚动自己的实现,请查看https://github.com/jgallen23/querystring

    【讨论】:

      【解决方案9】:
      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;
      };
      

      【讨论】:

        【解决方案10】:

        此解决方案处理 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) : {};
        }();
        

        用法:

        console.log('someParam GET value is', params['someParam']);
        

        【讨论】:

          【解决方案11】:

          如果你使用 AngularJS,你可以通过 $routeParams 使用 ngRoute 模块

          你必须在你的应用中添加一个模块

          angular.module('myApp', ['ngRoute'])
          

          现在您可以使用服务$routeParams

          .controller('AppCtrl', function($routeParams) {
            console.log($routeParams); // JSON object
          }
          

          【讨论】:

            【解决方案12】:

            这个使用正则表达式,如果参数不存在或没有任何值则返回null:

            function getQuery(q) {
               return (window.location.search.match(new RegExp('[?&]' + q + '=([^&]+)')) || [, null])[1];
            }
            

            【讨论】:

            • 是的,谢谢,这是我需要的 :)
            • 完美完成工作。谢谢!
            • 完美的代码,谢谢!
            • 完美且非常小的代码部分。谢谢。
            • 哇,不错的一个..
            【解决方案13】:

            将参数作为 JSON 对象获取:

            alert(getUrlParameters().toSource())
            
            function explode(delim, str)
            {
                return str.split(delim);
            }
            
            function getUrlParameters()
            {
                var out = {};
                var str = window.location.search.replace("?", "");
                var subs = explode('&', str);
                for(var i = 0; i < subs.length; ++i)
                {
                    var vals = explode('=', subs[i]);
                    out[vals[0]] = vals[1];
                }
                return out;
            }
            

            【讨论】:

              【解决方案14】:

              我创建了一个简单的 JavaScript 函数来从 URL 访问 GET 参数。

              只需包含此 JavaScript 源代码,您就可以访问 get 参数。 例如:在http://example.com/index.php?language=french 中,language 变量可以作为$_GET["language"] 访问。同样,所有参数的列表将作为数组存储在变量$_GET_Params 中。以下代码 sn-p 中提供了 JavaScript 和 HTML:

              <!DOCTYPE html>
              <html>
                <body>
                  <!-- This script is required -->
                  <script>
                  function $_GET() {
                    // Get the Full href of the page e.g. http://www.google.com/files/script.php?v=1.8.7&country=india
                    var href = window.location.href;
              
                    // Get the protocol e.g. http
                    var protocol = window.location.protocol + "//";
              
                    // Get the host name e.g. www.google.com
                    var hostname = window.location.hostname;
              
                    // Get the pathname e.g. /files/script.php
                    var pathname = window.location.pathname;
              
                    // Remove protocol part
                    var queries = href.replace(protocol, '');
              
                    // Remove host part
                    queries = queries.replace(hostname, '');
              
                    // Remove pathname part
                    queries = queries.replace(pathname, '');
              
                    // Presently, what is left in the variable queries is : ?v=1.8.7&country=india
              
                    // Perform query functions if present
                    if (queries != "" && queries != "?") {
              
                  // Remove question mark '?'
                      queries = queries.slice(1);
              
                      // Split all the different queries
                      queries = queries.split("&");
              
                      // Get the number of queries
                      var length = queries.length;
              
                      // Declare global variables to store keys and elements
                      $_GET_Params = new Array();
                      $_GET = {};
              
                      // Perform functions per query
                      for (var i  = 0; i < length; i++) {
              
                        // Get the present query
                        var key = queries[i];
              
                        // Split the query and the value
                        key = key.split("=");
              
                        // Assign value to the $_GET variable
                        $_GET[key[0]] = [key[1]];
              
                        // Assign value to the $_GET_Params variable
                        $_GET_Params[i] = key[0];
                      }
                    }
                  }
              
                  // Execute the function
                  $_GET();
                  </script>
                  <h1>GET Parameters</h1>
                  <h2>Try to insert some get parameter and access it through JavaScript</h2>
                </body>
              </html>

              【讨论】:

                【解决方案15】:

                这里我编写了这段代码来将 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 of getParameters
                console.log(getParameters(getNavUrl()));
                

                【讨论】:

                  【解决方案16】:

                  你应该使用 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/URLSearchParams https://polyfill.io/v2/docs/features/

                  【讨论】:

                  • 很遗憾这与 IE 不兼容 :'(
                  • 添加下面列出的 polyfill 代码 sn-p 来修补 IE 并将皱眉倒过来。
                  • @Alexey > 因为应该是var params = new URLSearchParams(window.location.search.slice(1));
                  • 这个doesn't work on iOS Safari,市场份额比IE大得多。
                  • 这是最有力的答案,无需使用发明的功能和大量代码
                  【解决方案17】:

                  这是另一个基于 Kat 和 Bakudan's 示例的示例,但使其更加通用。

                  function getParams ()
                  {
                      var result = {};
                      var tmp = [];
                  
                      location.search
                          .substr (1)
                          .split ("&")
                          .forEach (function (item)
                          {
                              tmp = item.split ("=");
                              result [tmp[0]] = decodeURIComponent (tmp[1]);
                          });
                  
                      return result;
                  }
                  
                  location.getParams = getParams;
                  
                  console.log (location.getParams());
                  console.log (location.getParams()["returnurl"]);
                  

                  【讨论】:

                  • 用户名“Kat”没有答案或评论。用户名可以随时更改。它指的是什么?
                  猜你喜欢
                  • 2017-05-14
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  相关资源
                  最近更新 更多