jQuery:如何获取url的参数?

发布于 2024-10-18 20:26:48 字数 1095 浏览 6 评论 0原文

jQuery 新手,我在获取服务器生成的 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 菜鸟有什么帮助吗?提前致谢!

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

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¶m2=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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

鸠书 2024-10-25 20:26:49

为此,您不需要 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)

演示

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

瀟灑尐姊 2024-10-25 20:26:49

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

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/

与风相奔跑 2024-10-25 20:26:49

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

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

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;
}
对你而言 2024-10-25 20:26:49

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

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)

searchParams.has('id') // true

let paramId = searchParams.get('id');
半寸时光 2024-10-25 20:26:49
function getURLParameter(name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
    );
}
function getURLParameter(name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
    );
}
黯然#的苍凉 2024-10-25 20:26:49

你的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 secondary = $.getUrlVars()["param2"];
  2. this.href 替换为 $('.popuptest a').attr("href")

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")
痕至 2024-10-25 20:26:49

来自此处

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

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

from here

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

// example.com?param1=name¶m2=&id=6
$.urlParam('param1'); // name
$.urlParam('id');        // 6
$.urlParam('param2');   // null
软糖 2024-10-25 20:26:49

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

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>
合约呢 2024-10-25 20:26:49

使用下面的代码有一段时间了,但最近发现 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];
 }
});

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];
 }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文