开发者

jQuery: How to get parameters of a url?

New to jQuery and I'm having tro开发者_运维知识库uble 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


You don't need jQuery for that purpose you can use the pure 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)

DEMO


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

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/


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


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


Jquery have in build functions for get param form URL.

var url="http://example.com/?id=76dc915c-b1c2-47f6-ae63-a3ea6ce78f2a";

let searchParams = new URLSearchParams(window.location.search)
Does sent exist?

searchParams.has('id') // true
Is it equal to "yes"?

let param = searchParams.get('id');


Your jquery could be

$(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")


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


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

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


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];
 }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜