使用jQuery获取查询字符串参数

时间:2022-08-24 12:38:15

Anyone know of a good way to write a jQuery extension to handle query string parameters? I basically want to extend the jQuery magic ($) function so I can do something like this:

有人知道编写jQuery扩展来处理查询字符串参数的好方法吗?我想要扩展jQuery魔术($)函数,这样我就可以这样做:

$('?search').val(); 

Which would give me the value "test" in the following URL: http://www.example.com/index.php?search=test.

它将在以下URL中为我提供值“test”:http://www.example.com/index.php?

I've seen a lot of functions that can do this in jQuery and Javascript, but I actually want to extend jQuery to work exactly as it is shown above. I'm not looking for a jQuery plugin, I'm looking for an extension to the jQuery method.

我见过很多函数可以在jQuery和Javascript中实现这一点,但实际上我希望扩展jQuery,使其工作与上面显示的完全一样。我不是在寻找jQuery插件,我是在寻找jQuery方法的扩展。

9 个解决方案

#1


90  

JQuery jQuery-URL-Parser plugin do the same job, for example to retrieve the value of search query string param, you can use

JQuery JQuery - url解析器插件做同样的工作,例如检索搜索查询字符串param的值,您可以使用

$.url().param('search');

This library is not actively maintained. As suggested by the author of the same plugin, you can use URI.js.

这个库没有被积极地维护。正如该插件作者所建议的,您可以使用URI.js。

Or you can use js-url instead. Its quite similar to the one below.

或者您也可以使用js-url。它和下面的很相似。

So you can access the query param like $.url('?search')

因此,您可以访问查询param,比如$.url('?search')

#2


81  

Why extend jQuery? What would be the benefit of extending jQuery vs just having a global function?

为什么扩展jQuery ?扩展jQuery与只拥有全局函数有什么好处?

function qs(key) {
    key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
    var match = location.search.match(new RegExp("[?&]"+key+"=([^&]+)(&|$)"));
    return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}

http://jsfiddle.net/gilly3/sgxcL/

http://jsfiddle.net/gilly3/sgxcL/

An alternative approach would be to parse the entire query string and store the values in an object for later use. This approach doesn't require a regular expression and extends the window.location object (but, could just as easily use a global variable):

另一种方法是解析整个查询字符串,并将值存储在对象中,以便以后使用。这种方法不需要正则表达式并扩展窗口。location对象(但是,同样可以使用全局变量):

location.queryString = {};
location.search.substr(1).split("&").forEach(function (pair) {
    if (pair === "") return;
    var parts = pair.split("=");
    location.queryString[parts[0]] = parts[1] &&
        decodeURIComponent(parts[1].replace(/\+/g, " "));
});

http://jsfiddle.net/gilly3/YnCeu/

http://jsfiddle.net/gilly3/YnCeu/

This version also makes use of Array.forEach(), which is unavailable natively in IE7 and IE8. It can be added by using the implementation at MDN, or you can use jQuery's $.each() instead.

这个版本还使用了Array.forEach(),这在IE7和IE8中是不可用的。它可以通过在MDN上的实现添加,也可以使用jQuery的$.each()。

#3


40  

This isn't my code sample, but I've used it in the past.

这不是我的代码示例,但我以前使用过它。

//First Add this to extend jQuery

    $.extend({
      getUrlVars: function(){
        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;
      },
      getUrlVar: function(name){
        return $.getUrlVars()[name];
      }
    });

    //Second call with this:
    // Get object of URL parameters
    var allVars = $.getUrlVars();

    // Getting URL var by its name
    var byName = $.getUrlVar('name');

#4


31  

Found this gem from our friends over at SitePoint. https://www.sitepoint.com/url-parameters-jquery/.

在SitePoint上,我们的朋友发现了这个宝石。https://www.sitepoint.com/url-parameters-jquery/。

Using PURE jQuery. I just used this and it worked. Tweaked it a bit for example sake.

使用纯jQuery。我只是用了这个,它起作用了。稍微调整了一下。

//URL is http://www.example.com/mypage?ref=registration&email=bobo@example.com

$.urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                      .exec(window.location.search);

    return (results !== null) ? results[1] || 0 : false;
}

console.log($.urlParam('ref')); //registration
console.log($.urlParam('email')); //bobo@example.com

Use as you will.

你会使用。

#5


11  

I wrote a little function where you only have to parse the name of the query parameter. So if you have: ?Project=12&Mode=200&date=2013-05-27 and you want the 'Mode' parameter you only have to parse the 'Mode' name into the function:

我编写了一个小函数,您只需解析查询参数的名称。因此,如果您有:?Project=12&Mode=200&date=2013-05-27并且您想要'Mode'参数,您只需将'Mode' name解析为函数:

function getParameterByName( name ){
    var regexS = "[\\?&]"+name+"=([^&#]*)", 
  regex = new RegExp( regexS ),
  results = regex.exec( window.location.search );
  if( results == null ){
    return "";
  } else{
    return decodeURIComponent(results[1].replace(/\+/g, " "));
  }
}

// example caller:
var result =  getParameterByName('Mode');

#6


7  

After years of ugly string parsing, there's a better way: URLSearchParams Let's have a look at how we can use this new API to get values from the location!

经过多年糟糕的字符串解析之后,有一种更好的方法:URLSearchParams让我们看看如何使用这个新的API从位置获取值!

// Assuming "?post=1234&action=edit"

/ /假设”? = 1234行动=编辑”

var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?

post=1234&action=edit&active=1"

UPDATE : IE is not supported

use this function instead of URLSearchParams

使用此函数代替URLSearchParams。

$.urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                      .exec(window.location.href);
    if (results == null) {
         return 0;
    }
    return results[1] || 0;
}

console.log($.urlParam('action')); //edit

#7


5  

Building on @Rob Neild's answer above, here is a pure JS adaptation that returns a simple object of decoded query string params (no %20's, etc).

基于上面@Rob Neild的回答,这里有一个纯JS改编,它返回一个简单的解码查询字符串params对象(no %20's,等等)。

function parseQueryString () {
  var parsedParameters = {},
    uriParameters = location.search.substr(1).split('&');

  for (var i = 0; i < uriParameters.length; i++) {
    var parameter = uriParameters[i].split('=');
    parsedParameters[parameter[0]] = decodeURIComponent(parameter[1]);
  }

  return parsedParameters;
}

#8


0  

Written in Vanilla Javascript

用香草Javascript

     //Get URL
     var loc = window.location.href;
     console.log(loc);
     var index = loc.indexOf("?");
     console.log(loc.substr(index+1));
     var splitted = loc.substr(index+1).split('&');
     console.log(splitted);
     var paramObj = [];
     for(var i=0;i<splitted.length;i++){
         var params = splitted[i].split('=');
         var key = params[0];
         var value = params[1];
         var obj = {
             [key] : value
         };
         paramObj.push(obj);
         }
    console.log(paramObj);
    //Loop through paramObj to get all the params in query string.

#9


0  

function parseQueryString(queryString) {
    if (!queryString) {
        return false;
    }

    let queries = queryString.split("&"), params = {}, temp;

    for (let i = 0, l = queries.length; i < l; i++) {
        temp = queries[i].split('=');
        if (temp[1] !== '') {
            params[temp[0]] = temp[1];
        }
    }
    return params;
}

I use this.

我用这个。

#1


90  

JQuery jQuery-URL-Parser plugin do the same job, for example to retrieve the value of search query string param, you can use

JQuery JQuery - url解析器插件做同样的工作,例如检索搜索查询字符串param的值,您可以使用

$.url().param('search');

This library is not actively maintained. As suggested by the author of the same plugin, you can use URI.js.

这个库没有被积极地维护。正如该插件作者所建议的,您可以使用URI.js。

Or you can use js-url instead. Its quite similar to the one below.

或者您也可以使用js-url。它和下面的很相似。

So you can access the query param like $.url('?search')

因此,您可以访问查询param,比如$.url('?search')

#2


81  

Why extend jQuery? What would be the benefit of extending jQuery vs just having a global function?

为什么扩展jQuery ?扩展jQuery与只拥有全局函数有什么好处?

function qs(key) {
    key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
    var match = location.search.match(new RegExp("[?&]"+key+"=([^&]+)(&|$)"));
    return match && decodeURIComponent(match[1].replace(/\+/g, " "));
}

http://jsfiddle.net/gilly3/sgxcL/

http://jsfiddle.net/gilly3/sgxcL/

An alternative approach would be to parse the entire query string and store the values in an object for later use. This approach doesn't require a regular expression and extends the window.location object (but, could just as easily use a global variable):

另一种方法是解析整个查询字符串,并将值存储在对象中,以便以后使用。这种方法不需要正则表达式并扩展窗口。location对象(但是,同样可以使用全局变量):

location.queryString = {};
location.search.substr(1).split("&").forEach(function (pair) {
    if (pair === "") return;
    var parts = pair.split("=");
    location.queryString[parts[0]] = parts[1] &&
        decodeURIComponent(parts[1].replace(/\+/g, " "));
});

http://jsfiddle.net/gilly3/YnCeu/

http://jsfiddle.net/gilly3/YnCeu/

This version also makes use of Array.forEach(), which is unavailable natively in IE7 and IE8. It can be added by using the implementation at MDN, or you can use jQuery's $.each() instead.

这个版本还使用了Array.forEach(),这在IE7和IE8中是不可用的。它可以通过在MDN上的实现添加,也可以使用jQuery的$.each()。

#3


40  

This isn't my code sample, but I've used it in the past.

这不是我的代码示例,但我以前使用过它。

//First Add this to extend jQuery

    $.extend({
      getUrlVars: function(){
        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;
      },
      getUrlVar: function(name){
        return $.getUrlVars()[name];
      }
    });

    //Second call with this:
    // Get object of URL parameters
    var allVars = $.getUrlVars();

    // Getting URL var by its name
    var byName = $.getUrlVar('name');

#4


31  

Found this gem from our friends over at SitePoint. https://www.sitepoint.com/url-parameters-jquery/.

在SitePoint上,我们的朋友发现了这个宝石。https://www.sitepoint.com/url-parameters-jquery/。

Using PURE jQuery. I just used this and it worked. Tweaked it a bit for example sake.

使用纯jQuery。我只是用了这个,它起作用了。稍微调整了一下。

//URL is http://www.example.com/mypage?ref=registration&email=bobo@example.com

$.urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                      .exec(window.location.search);

    return (results !== null) ? results[1] || 0 : false;
}

console.log($.urlParam('ref')); //registration
console.log($.urlParam('email')); //bobo@example.com

Use as you will.

你会使用。

#5


11  

I wrote a little function where you only have to parse the name of the query parameter. So if you have: ?Project=12&Mode=200&date=2013-05-27 and you want the 'Mode' parameter you only have to parse the 'Mode' name into the function:

我编写了一个小函数,您只需解析查询参数的名称。因此,如果您有:?Project=12&Mode=200&date=2013-05-27并且您想要'Mode'参数,您只需将'Mode' name解析为函数:

function getParameterByName( name ){
    var regexS = "[\\?&]"+name+"=([^&#]*)", 
  regex = new RegExp( regexS ),
  results = regex.exec( window.location.search );
  if( results == null ){
    return "";
  } else{
    return decodeURIComponent(results[1].replace(/\+/g, " "));
  }
}

// example caller:
var result =  getParameterByName('Mode');

#6


7  

After years of ugly string parsing, there's a better way: URLSearchParams Let's have a look at how we can use this new API to get values from the location!

经过多年糟糕的字符串解析之后,有一种更好的方法:URLSearchParams让我们看看如何使用这个新的API从位置获取值!

// Assuming "?post=1234&action=edit"

/ /假设”? = 1234行动=编辑”

var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?

post=1234&action=edit&active=1"

UPDATE : IE is not supported

use this function instead of URLSearchParams

使用此函数代替URLSearchParams。

$.urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                      .exec(window.location.href);
    if (results == null) {
         return 0;
    }
    return results[1] || 0;
}

console.log($.urlParam('action')); //edit

#7


5  

Building on @Rob Neild's answer above, here is a pure JS adaptation that returns a simple object of decoded query string params (no %20's, etc).

基于上面@Rob Neild的回答,这里有一个纯JS改编,它返回一个简单的解码查询字符串params对象(no %20's,等等)。

function parseQueryString () {
  var parsedParameters = {},
    uriParameters = location.search.substr(1).split('&');

  for (var i = 0; i < uriParameters.length; i++) {
    var parameter = uriParameters[i].split('=');
    parsedParameters[parameter[0]] = decodeURIComponent(parameter[1]);
  }

  return parsedParameters;
}

#8


0  

Written in Vanilla Javascript

用香草Javascript

     //Get URL
     var loc = window.location.href;
     console.log(loc);
     var index = loc.indexOf("?");
     console.log(loc.substr(index+1));
     var splitted = loc.substr(index+1).split('&');
     console.log(splitted);
     var paramObj = [];
     for(var i=0;i<splitted.length;i++){
         var params = splitted[i].split('=');
         var key = params[0];
         var value = params[1];
         var obj = {
             [key] : value
         };
         paramObj.push(obj);
         }
    console.log(paramObj);
    //Loop through paramObj to get all the params in query string.

#9


0  

function parseQueryString(queryString) {
    if (!queryString) {
        return false;
    }

    let queries = queryString.split("&"), params = {}, temp;

    for (let i = 0, l = queries.length; i < l; i++) {
        temp = queries[i].split('=');
        if (temp[1] !== '') {
            params[temp[0]] = temp[1];
        }
    }
    return params;
}

I use this.

我用这个。