是否有一种通过jQuery(或不使用)检索查询字符串值的无插件方法?

如果是,怎么办?如果没有,是否有插件可以这样做?


当前回答

tl;博士

一个快速、完整的解决方案,可处理多值键和编码字符。

// using ES5   (200 characters)
var qd = {};
if (location.search) location.search.substr(1).split("&").forEach(function(item) {var s = item.split("="), k = s[0], v = s[1] && decodeURIComponent(s[1]); (qd[k] = qd[k] || []).push(v)})

// using ES6   (23 characters cooler)
var qd = {};
if (location.search) location.search.substr(1).split`&`.forEach(item => {let [k,v] = item.split`=`; v = v && decodeURIComponent(v); (qd[k] = qd[k] || []).push(v)})

// as a function with reduce
function getQueryParams() {
  return location.search
    ? location.search.substr(1).split`&`.reduce((qd, item) => {let [k,v] = item.split`=`; v = v && decodeURIComponent(v); (qd[k] = qd[k] || []).push(v); return qd}, {})
    : {}
}

多行:

var qd = {};
if (location.search) location.search.substr(1).split("&").forEach(function(item) {
    var s = item.split("="),
        k = s[0],
        v = s[1] && decodeURIComponent(s[1]); //  null-coalescing / short-circuit
    //(k in qd) ? qd[k].push(v) : qd[k] = [v]
    (qd[k] = qd[k] || []).push(v) // null-coalescing / short-circuit
})

这是什么代码。。。“零合并”,短路评估ES6解构赋值、箭头函数、模板字符串####示例:

"?a=1&b=0&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"
> qd
a: ["1", "5", "t e x t"]
b: ["0"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]

> qd.a[1]    // "5"
> qd["a"][1] // "5"


阅读更多。。。关于Vanilla JavaScript解决方案。

要访问URL的不同部分,请使用位置。(搜索|哈希)

最简单(虚拟)解决方案

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

正确处理空钥匙。使用找到的最后一个值覆盖多键。

"?a=1&b=0&c=3&d&e&a=5"
> queryDict
a: "5"
b: "0"
c: "3"
d: undefined
e: undefined

多值键

简单的密钥检查(字典中的项目)?dict.item.push(val):dict.item=[val]

var qd = {};
location.search.substr(1).split("&").forEach(function(item) {(item.split("=")[0] in qd) ? qd[item.split("=")[0]].push(item.split("=")[1]) : qd[item.split("=")[0]] = [item.split("=")[1]]})

现在返回数组。按qd.key[index]或qd[key][index]访问值

> qd
a: ["1", "5"]
b: ["0"]
c: ["3"]
d: [undefined]
e: [undefined]

编码字符?

对第二次或两次拆分使用decodeURIComponent()。

var qd = {};
location.search.substr(1).split("&").forEach(function(item) {var k = item.split("=")[0], v = decodeURIComponent(item.split("=")[1]); (k in qd) ? qd[k].push(v) : qd[k] = [v]})

####示例:

"?a=1&b=0&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"
> qd
a: ["1", "5", "t e x t"]
b: ["0"]
c: ["3"]
d: ["undefined"]  // decodeURIComponent(undefined) returns "undefined" !!!*
e: ["undefined", "http://w3schools.com/my test.asp?name=ståle&car=saab"]


# From comments **\*!!!** Please note, that `decodeURIComponent(undefined)` returns string `"undefined"`. The solution lies in a simple usage of [`&&`][5], which ensures that `decodeURIComponent()` is not called on undefined values. _(See the "complete solution" at the top.)_
v = v && decodeURIComponent(v);

If the querystring is empty (`location.search == ""`), the result is somewhat misleading `qd == {"": undefined}`. It is suggested to check the querystring before launching the parsing function likeso:
if (location.search) location.search.substr(1).split("&").forEach(...)

其他回答

下面是我将Andy E的优秀解决方案打造成一个成熟的jQuery插件的尝试:

;(function ($) {
    $.extend({      
        getQueryString: function (name) {           
            function parseParams() {
                var params = {},
                    e,
                    a = /\+/g,  // Regex for replacing addition symbol with a space
                    r = /([^&=]+)=?([^&]*)/g,
                    d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
                    q = window.location.search.substring(1);

                while (e = r.exec(q))
                    params[d(e[1])] = d(e[2]);

                return params;
            }

            if (!this.queryStringParams)
                this.queryStringParams = parseParams(); 

            return this.queryStringParams[name];
        }
    });
})(jQuery);

语法为:

var someVar = $.getQueryString('myParam');

两全其美!

Use:

  $(document).ready(function () {
      var urlParams = {};
      (function () {
          var match,
          pl = /\+/g, // Regex for replacing addition symbol with a space
              search = /([^&=]+)=?([^&]*)/g,
              decode = function (s) {
                  return decodeURIComponent(s.replace(pl, " "));
              },
              query = window.location.search.substring(1);

          while (match = search.exec(query))
              urlParams[decode(match[1])] = decode(match[2]);
      })();
      if (urlParams["q1"] === 1) {
          return 1;
      }

请检查并让我知道您的意见。另请参阅How to get querystring value using jQuery。

这个很好用。其他一些答案中的正则表达式引入了不必要的开销。

function getQuerystring(key) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == key) {
            return pair[1];
        }
    }
}

从这里取的

function GET() {
        var data = [];
        for(x = 0; x < arguments.length; ++x)
            data.push(location.href.match(new RegExp("/\?".concat(arguments[x],"=","([^\n&]*)")))[1])
                return data;
    }


example:
data = GET("id","name","foo");
query string : ?id=3&name=jet&foo=b
returns:
    data[0] // 3
    data[1] // jet
    data[2] // b
or
    alert(GET("id")[0]) // return 3

试试看:

String.prototype.getValueByKey = function(k){
    var p = new RegExp('\\b'+k+'\\b','gi');
    return this.search(p) != -1 ? decodeURIComponent(this.substr(this.search(p)+k.length+1).substr(0,this.substr(this.search(p)+k.length+1).search(/(&|;|$)/))) : "";
};

然后这样称呼:

if(location.search != "") location.search.getValueByKey("id");

您还可以将此用于cookie:

if(navigator.cookieEnabled) document.cookie.getValueByKey("username");

这只适用于key=value[&|;|$]。。。将无法处理对象/数组。

如果您不想使用String.prototype。。。将其移动到函数并将字符串作为参数传递