jQuery:如何获取url的参数?

kuuvgm7e  于 2023-04-11  发布在  jQuery
关注(0)|答案(9)|浏览(192)

刚接触jQuery,我在获取服务器生成的url参数时遇到了麻烦。我有一个这样的url:

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

我的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;
  });
});

点击链接应该会显示“2”,但是我什么也没有得到...对jQuery noob有任何帮助吗?提前感谢!
我在一个博客上发现了这个:http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html

gojuced7

gojuced71#

你不需要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, " "));
}

你可以这样调用函数.. getParameterByName(param1,href of your link)
DEMO

1bqhqjot

1bqhqjot2#

一个小的改进,只解析一次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/

af7jpaap

af7jpaap3#

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

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

goucqfw64#

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

nafvub8i5#

Jquery内置了获取URL参数的函数。

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

let searchParams = new URLSearchParams(window.location.search)

searchParams.has('id') // true

let paramId = searchParams.get('id');
kognpnkq

kognpnkq6#

你的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;
  });
});

注意事项:
1.$.getUrlVars in line - var second = $.getUrlVars()[“param2”];

  1. this.href被替换为$('. popuptest a').attr(“href”)
ktecyv1j

ktecyv1j7#

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
3hvapo4f

3hvapo4f8#

如此简单,您可以使用任何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>
pjngdqdw

pjngdqdw9#

使用下面的代码有一段时间了,但最近发现URL中的base64_encode字符串有一个问题,结尾处有==,比如:/index.php?a=1&b=2&c=Mw==&d=4.
使用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];
 }
});

相关问题