小编典典

如何获取JavaScript中的查询字符串值?

javascript

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

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


阅读 549

收藏
2020-04-22

共2个答案

小编典典

const urlParams = new URLSearchParams(window.location.search);
const myParam = urlParams.get(‘myParam’);

原版的

为此,您不需要jQuery。您可以只使用一些纯JavaScript:

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

用法:

// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
var bar = getParameterByName('bar'); // "" (present with empty value)
var baz = getParameterByName('baz'); // "" (present with no value)
var qux = getParameterByName('qux'); // null (absent)

注意:如果一个参数多次出现(?foo=lorem&foo=ipsum),您将获得第一个值(lorem)。对此没有标准,用法也有所不同

2020-04-22
小编典典

一种新功能将是检索重复的参数,如下所示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]);
        }
    }
})();
2020-04-22