jQuery: How to get parameters of a url?

2019-01-13 21:44发布

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

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

my jquery function looks like so:

$(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!

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

8条回答
Ridiculous、
2楼-- · 2019-01-13 22:34

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

function getParameterByName(name) {
 return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
查看更多
在下西门庆
3楼-- · 2019-01-13 22:34

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.

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

 $.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];
 }
});
查看更多
登录 后发表回答