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

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


当前回答

下面是我将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');

两全其美!

其他回答

在简单的JavaScript代码中保持简单:

function qs(key) {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars[key];
}

从JavaScript代码中的任何位置调用它:

var result = qs('someKey');
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

这里发布的一些解决方案效率低下。每次脚本需要访问参数时重复正则表达式搜索是完全不必要的,一个函数将参数拆分为关联数组样式对象就足够了。如果您不使用HTML5历史API,则每次加载页面只需要一次。这里的其他建议也无法正确解码URL。

var urlParams;
(window.onpopstate = 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);
  
    urlParams = {};
    while (match = search.exec(query))
       urlParams[decode(match[1])] = decode(match[2]);
})();

示例查询字符串:

?i=main&mode=front&sid=de8d49b78a85a322c4155015fdce22c4&enc=+Hello%20&empty

结果:

 urlParams = {
    enc: " Hello ",
    i: "main",
    mode: "front",
    sid: "de8d49b78a85a322c4155015fdce22c4",
    empty: ""
}

alert(urlParams["mode"]);
// -> "front"

alert("empty" in urlParams);
// -> true

这也可以很容易地改进为处理数组样式的查询字符串。这里有一个这样的例子,但由于RFC 3986中没有定义数组样式参数,所以我不会用源代码污染这个答案。对于那些对“污染”版本感兴趣的人,请看下面坎贝尔的答案。

此外,正如评论中指出的;是key=value对的合法分隔符。它需要更复杂的正则表达式来处理;或&,我认为这是不必要的,因为这很少见;我想说,更不可能两者都使用。如果您需要支持;而不是&,只是在正则表达式中交换它们。


If you're using a server-side preprocessing language, you might want to use its native JSON functions to do the heavy lifting for you. For example, in PHP you can write:
<script>var urlParams = <?php echo json_encode($_GET, JSON_HEX_TAG);?>;</script>

简单多了!

#已更新

一个新的功能是检索重复的参数,如下myparam=1和myparam=2。然而,没有一个规范,目前的大多数方法都遵循数组的生成。

myparam = ["1", "2"]

因此,这是管理它的方法:

let urlParams = {};
(window.onpopstate = function () {
    let 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)) {
        if (decode(match[1]) in urlParams) {
            if (!Array.isArray(urlParams[decode(match[1])])) {
                urlParams[decode(match[1])] = [urlParams[decode(match[1])]];
            }
            urlParams[decode(match[1])].push(decode(match[2]));
        } else {
            urlParams[decode(match[1])] = decode(match[2]);
        }
    }
})();

我认为这是实现这一点的准确和简洁的方法(修改自http://css-tricks.com/snippets/javascript/get-url-variables/):

function getQueryVariable(variable) {

    var query = window.location.search.substring(1),            // Remove the ? from the query string.
        vars = query.split("&");                                // Split all values by ampersand.

    for (var i = 0; i < vars.length; i++) {                     // Loop through them...
        var pair = vars[i].split("=");                          // Split the name from the value.
        if (pair[0] == variable) {                              // Once the requested value is found...
            return ( pair[1] == undefined ) ? null : pair[1];   // Return null if there is no value (no equals sign), otherwise return the value.
        }
    }

    return undefined;                                           // Wasn't found.

}

只需使用两个拆分:

function get(n) {
    var half = location.search.split(n + '=')[1];
    return half !== undefined ? decodeURIComponent(half.split('&')[0]) : null;
}

我读了之前所有的答案,也读了更完整的答案。但我认为这是最简单快捷的方法。您可以检查这个jsPerf基准

要解决Rup评论中的问题,请通过将第一行更改为下面的两行来添加条件拆分。但绝对的准确性意味着它现在比正则表达式慢(参见jsPerf)。

function get(n) {
    var half = location.search.split('&' + n + '=')[1];
    if (!half) half = location.search.split('?' + n + '=')[1];
    return half !== undefined ? decodeURIComponent(half.split('&')[0]) : null;
}

所以如果你知道你不会遇到Rup的反案,这就赢了。否则,使用正则表达式。

或者,如果您可以控制查询字符串,并且可以保证您试图获取的值永远不会包含任何URL编码字符(在值中包含这些字符是个坏主意)-您可以使用以下是第一个选项的略为简化和可读的版本:函数getQueryStringValueByName(名称){var queryStringFromStartOfValue=位置.search.split(名称+“=”)[1];返回queryStringFromStartOfValue!==未定义?queryStringFromStartOfValue.split(“&”)[0]:null;