jQuery:如何获取网址的参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5073859/
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-26 18:31:31  来源:igfitidea点击:

jQuery: How to get parameters of a url?

jqueryparametersgethrefparam

提问by thedeepfield

New to jQuery and I'm having trouble getting the parameters of a url that my server generates. I have a url like this:

jQuery 新手,我在获取服务器生成的 url 参数时遇到问题。我有一个这样的网址:

<span class="popuptest"><a href="www.example.com/test?param1=1&param2=2">find param</a></span>

my jquery function looks like so:

我的 jquery 函数如下所示:

$(function() {
  $('.popuptest a').live('click', function(event) {
  $.extend({
    getUrlVars: function(){
      var vars = [], hash;
      var hashes = this.href.slice(this.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];
    }
  });
  var second = getUrlVars()["param2"];
  alert(second);
  return false;
  });
});

clicking on the link should show me "2", however I get nothing... any help for a jQuery noob? thanks in advance!

单击链接应该显示“2”,但是我什么也没得到……对 jQuery 菜鸟有什么帮助吗?提前致谢!

I found this on a blog: http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html

我在博客上找到了这个:http: //jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html

回答by Vivek

You don't need jQuery for that purpose you can use the pure JavaScript:

为此,您不需要 jQuery,您可以使用纯 JavaScript:

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

and you can call the function in this way..getParameterByName(param1,href of your link)

你可以用这种方式调用函数..getParameterByName(param1,href of your link)

DEMO

演示

回答by shak

small improvement, parse the url only once, return array or params:

小改进,只解析一次 url,返回数组或参数:

function getURLParameters(url){

    var result = {};
    var hashIndex = url.indexOf("#");
    if (hashIndex > 0)
       url = url.substr(0, hashIndex);        
    var searchIndex = url.indexOf("?");
    if (searchIndex == -1 ) return result;
    var sPageURL = url.substring(searchIndex +1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++)
    {       
        var sParameterName = sURLVariables[i].split('=');      
        result[sParameterName[0]] = sParameterName[1];
    }
    return result;
}

http://jsfiddle.net/shakhal/gXM3u/

http://jsfiddle.net/shakhal/gXM3u/

回答by Masoud Mustamandi

it's so easy, all you have to do is put the variable name that you want it from the URL into this function then it will return you the value of URL variable

很简单,你所要做的就是把你想要的变量名从 URL 中放入这个函数中,然后它会返回给你 URL 变量的值

function getParameterByName(name) {
 return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}

回答by Xman Classical

function getURLParameter(name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
    );
}

回答by user237865

Your jquery could be

你的 jquery 可能是

$(function() {  
 $('.popuptest a').live('click', function(event) {
 $.extend({     getUrlVars: function(){
  var vars = [], hash;
  var hashes = $('.popuptest a').attr("href").slice($('.popuptest     a').attr("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];
}
  });
  var second = $.getUrlVars()["param2"];
  alert(second);
  return false;
  });
});

things to note:

注意事项:

  1. $.getUrlVars in line - var second = $.getUrlVars()["param2"];
  2. this.href is replaced to $('.popuptest a').attr("href")
  1. $.getUrlVars in line - var second = $.getUrlVars()["param2"];
  2. this.href 被替换为 $('.popuptest a').attr("href")

回答by efirvida

from here

这里

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

// example.com?param1=name&param2=&id=6
$.urlParam('param1'); // name
$.urlParam('id');        // 6
$.urlParam('param2');   // null

回答by Balaji Rajendran

So simple you can use any url and get value in Javascript.And this is Complete set of codes

如此简单,您可以使用任何 url 并在 Javascript 中获取值。这是完整的代码集

<!DOCTYPE html>
<html>
<head>
<script>
var tech = getQueryVariable('filename');
function getQueryVariable(variable)
{
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
}
alert(tech);
</script>
</head>
<body>
<p>Get parameters of a url</p>
</body>
</html>

回答by Bazardshoxer

Using code below for some time, but recently discoverd a problem with an base64_encode string in the URL, having == at the end, like: /index.php?a=1&b=2&c=Mw==&d=4.

使用下面的代码一段时间,但最近发现 URL 中的 base64_encode 字符串有问题,末尾有 ==,例如:/index.php?a=1&b=2&c=Mw==&d=4。

Using getUrlVar("c") gives me 'Mw' as result, but this should be 'Mw==', so added an extra line:

使用 getUrlVar("c") 给了我 'Mw' 作为结果,但这应该是 'Mw==',所以添加了一个额外的行:

 $.extend({
  getUrlVars: function(){
   var vars = [], hash;
   var hashes = $('.popuptest a').attr("href").slice($('.popuptest a').attr("href").indexOf('?') + 1).split('&');
   for(var i = 0; i < hashes.length; i++)
   {
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    if (hash.length > 2) hash[1] = hash.slice(1).join('=');
    vars[hash[0]] = hash[1];
   }
   return vars;
  },
  getUrlVar: function(name){
   return $.getUrlVars()[name];
 }
});