使用 jQuery / Javascript (querystring) 获取查询字符串参数 url 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7731778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:21:56  来源:igfitidea点击:

Get query string parameters url values with jQuery / Javascript (querystring)

javascriptjqueryurljquery-pluginsquery-string

提问by TroySteven

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.

这将使我在下面的网址值“测试”: http://www.example.com/index.php?search=test

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 方法的扩展。

采纳答案by Saurin

After years of ugly string parsing, there's a better way: URLSearchParamsLet'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"

// 假设“?post=1234&action=edit”

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

更新:不支持 IE

use this function from an answer belowinstead of URLSearchParams

下面的答案中使用此函数而不是URLSearchParams

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

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

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

回答by gilly3

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.locationobject (but, could just as easily use a global variable):

另一种方法是解析整个查询字符串并将值存储在一个对象中以备后用。这种方法不需要正则表达式并扩展window.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()代替。

回答by RameshVel

JQuery jQuery-URL-Parserplugin do the same job, for example to retrieve the value of searchquery string param, you can use

JQuery jQuery-URL-Parser插件做同样的工作,例如检索搜索查询字符串参数的值,你可以使用

$.url().param('search');
$.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-urlinstead. Its quite similar to the one below.

或者您可以改用js-url。它与下面的非常相似。

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

所以你可以像这样访问查询参数 $.url('?search')

回答by ClosDesign

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 protected]

$.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')); //[email protected]

Use as you will.

随意使用。

回答by Rob Nield

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');

回答by Plippie

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”名称解析为函数:

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');

回答by Plippie

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 改编版,它返回一个简单的解码查询字符串参数对象(没有 %20 等)。

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;
}

回答by manish Prasad

Written in Vanilla Javascript

用 Vanilla 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.

回答by donvercety

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.

我用这个。