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

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


当前回答

查看此帖子或使用此:

<script type="text/javascript" language="javascript">
    $(document).ready(function()
    {
        var urlParams = {};
        (function ()
        {
            var match,
            pl= /\+/g,  // Regular expression 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;
        }
    });
</script>

其他回答

只是另一个建议。插件Purl允许检索URL的所有部分,包括锚点、主机等。

它可以与jQuery一起使用,也可以不使用jQuery。

用法很简单,很酷:

var url = $.url('http://example.com/folder/dir/index.html?item=value'); // jQuery version
var url = purl('http://example.com/folder/dir/index.html?item=value'); // plain JS version
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'

然而,截至2014年11月11日,Purl不再被维护,作者建议改用URI.js。jQuery插件的不同之处在于它关注元素-对于字符串使用,只需直接使用URI,无论是否使用jQuery。类似的代码看起来是这样的,更完整的文档如下:

var url = new URI('http://example.com/folder/dir/index.html?item=value'); // plain JS version
url.protocol(); // returns 'http'
url.path(); // returns '/folder/dir/index.html'

ES2015(ES6)

getQueryStringParams = query => {
    return query
        ? (/^[?#]/.test(query) ? query.slice(1) : query)
            .split('&')
            .reduce((params, param) => {
                    let [key, value] = param.split('=');
                    params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
                    return params;
                }, {}
            )
        : {}
};

没有jQuery

var qs = (function(a) {
    if (a == "") return {};
    var b = {};
    for (var i = 0; i < a.length; ++i)
    {
        var p=a[i].split('=', 2);
        if (p.length == 1)
            b[p[0]] = "";
        else
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return b;
})(window.location.search.substr(1).split('&'));

URL如下?topic=123&name=query+string,将返回以下内容:

qs["topic"];    // 123
qs["name"];     // query string
qs["nothere"];  // undefined (object)

Google方法

撕扯谷歌的代码,我找到了他们使用的方法:getUrlParameters

function (b) {
    var c = typeof b === "undefined";
    if (a !== h && c) return a;
    for (var d = {}, b = b || k[B][vb], e = b[p]("?"), f = b[p]("#"), b = (f === -1 ? b[Ya](e + 1) : [b[Ya](e + 1, f - e - 1), "&", b[Ya](f + 1)][K](""))[z]("&"), e = i.dd ? ia : unescape, f = 0, g = b[w]; f < g; ++f) {
        var l = b[f][p]("=");
        if (l !== -1) {
            var q = b[f][I](0, l),
                l = b[f][I](l + 1),
                l = l[Ca](/\+/g, " ");
            try {
                d[q] = e(l)
            } catch (A) {}
        }
    }
    c && (a = d);
    return d
}

这是模糊的,但可以理解。它无法工作,因为某些变量未定义。

他们开始在url上查找参数?并且还从散列#中。然后,对于每个参数,它们以等号b[f][p](“=”)分割(看起来像indexOf,它们使用字符的位置来获取键/值)。拆分后,他们检查参数是否有值,如果有值,则存储d的值,否则继续。

最后返回对象d,处理转义和+符号。这个对象和我的一样,它有相同的行为。


我的方法作为jQuery插件

(function($) {
    $.QueryString = (function(paramsArray) {
        let params = {};

        for (let i = 0; i < paramsArray.length; ++i)
        {
            let param = paramsArray[i]
                .split('=', 2);
            
            if (param.length !== 2)
                continue;
            
            params[param[0]] = decodeURIComponent(param[1].replace(/\+/g, " "));
        }
            
        return params;
    })(window.location.search.substr(1).split('&'))
})(jQuery);

用法

//Get a param
$.QueryString.param
//-or-
$.QueryString["param"]
//This outputs something like...
//"val"

//Get all params as object
$.QueryString
//This outputs something like...
//Object { param: "val", param2: "val" }

//Set a param (only in the $.QueryString object, doesn't affect the browser's querystring)
$.QueryString.param = "newvalue"
//This doesn't output anything, it just updates the $.QueryString object

//Convert object into string suitable for url a querystring (Requires jQuery)
$.param($.QueryString)
//This outputs something like...
//"param=newvalue&param2=val"

//Update the url/querystring in the browser's location bar with the $.QueryString object
history.replaceState({}, '', "?" + $.param($.QueryString));
//-or-
history.pushState({}, '', "?" + $.param($.QueryString));

性能测试(针对正则表达式方法的拆分方法)(jsPerf)

准备代码:方法声明

拆分测试代码

var qs = window.GetQueryString(query);

var search = qs["q"];
var value = qs["value"];
var undef = qs["undefinedstring"];

Regex测试代码

var search = window.getParameterByName("q");
var value = window.getParameterByName("value");
var undef = window.getParameterByName("undefinedstring");

在Windows Server 2008 R2/7 x64上的Firefox 4.0 x86中测试

拆分方法:最快144780±2.17%Regex方法:13891±0.85%|90%慢

我接受了这个答案,并添加了对可选地将URL作为参数传入的支持;返回到window.location.search。显然,这对于从不是当前页面的URL获取查询字符串参数非常有用:

(function($, undef) {
  $.QueryString = function(url) {
    var pairs, qs = null, index, map = {};
    if(url == undef){
      qs = window.location.search.substr(1);
    }else{
      index = url.indexOf('?');
      if(index == -1) return {};
      qs = url.substring(index+1);
    }
    pairs = qs.split('&');
    if (pairs == "") return {};
    for (var i = 0; i < pairs.length; ++i)
    {
      var p = pairs[i].split('=');
      if(p.length != 2) continue;
      map[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    return map;
  };
})(jQuery);

这是我自己的看法。第一个函数将URL字符串解码为名称/值对的对象:

url_args_decode = function (url) {
  var args_enc, el, i, nameval, ret;
  ret = {};
  // use the DOM to parse the URL via an 'a' element
  el = document.createElement("a");
  el.href = url;
  // strip off initial ? on search and split
  args_enc = el.search.substring(1).split('&');
  for (i = 0; i < args_enc.length; i++) {
    // convert + into space, split on =, and then decode 
    args_enc[i].replace(/\+/g, ' ');
    nameval = args_enc[i].split('=', 2);
    ret[decodeURIComponent(nameval[0])]=decodeURIComponent(nameval[1]);
  }
  return ret;
};

另外,如果您更改了一些参数,可以使用第二个函数将参数数组放回URL字符串中:

url_args_replace = function (url, args) {
  var args_enc, el, name;
  // use the DOM to parse the URL via an 'a' element
  el = document.createElement("a");
  el.href = url;
  args_enc = [];
  // encode args to go into url
  for (name in args) {
    if (args.hasOwnProperty(name)) {
      name = encodeURIComponent(name);
      args[name] = encodeURIComponent(args[name]);
      args_enc.push(name + '=' + args[name]);
    }
  }
  if (args_enc.length > 0) {
    el.search = '?' + args_enc.join('&');
  } else {
    el.search = '';
  }
  return el.href;
};

以下代码将创建一个具有两个方法的对象:

isKeyExist:检查是否存在特定参数getValue:获取特定参数的值。

 

var QSParam = new function() {
       var qsParm = {};
       var query = window.location.search.substring(1);
       var params = query.split('&');
       for (var i = 0; i < params.length; i++) {
           var pos = params[i].indexOf('=');
           if (pos > 0) {
               var key = params[i].substring(0, pos);
               var val = params[i].substring(pos + 1);
               qsParm[key] = val;
           }
       }
       this.isKeyExist = function(query){
           if(qsParm[query]){
               return true;
           }
           else{
              return false;
           }
       };
       this.getValue = function(query){
           if(qsParm[query])
           {
               return qsParm[query];
           }
           throw "URL does not contain query "+ query;
       }
};