从文本链接获取URL参数,并将其发送到AJAX调用

Get URL parameters from text link and post to AJAX call

本文关键字:调用 AJAX 链接 文本 获取 URL 参数      更新时间:2023-09-26

我目前正在开发一些jQuery,它将允许用户从文本链接进行AJAX调用。这是没有问题的,但文本链接有参数,我需要发送给AJAX请求,以使其正确执行。

我的文本链接看起来像这样:

<a href="?affiliate=one&voteType=two">Click here</a>
这是我的jQuery:
function getUrlParam(name)
{
  name = name.replace(/['[]/,"'''[").replace(/[']]/,"''']");
  var regexS = "[''?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

/* Let's create a function that will allow us to vote on the hosts */
function hostVote() {
/* These variables are used to determine the button clicked */
    var affiliate = getUrlParam('affiliate');
    var voteType = getUrlParam('voteType');
    $.ajax({
      cache: false,
      type: "POST",
        url: "/php/hostvote.php",
        data: "affilate=" + affiliate + "&voteType=" + voteType +"",
        success: voteSubmitted
    });
    function voteSubmitted() {
        alert('Thanks for voting');
        $(this).addClass('yes');
    }
    return false;   
};
$("a.vote").click(hostVote);

这个代码的问题是我不能提交链接,在函数执行之前把任何参数放在url中,导致空的附属和voteType变量。

有人能帮忙吗?

更好的方法是将所需的数据存储在链接的data-*属性中。这将使检索相应数据变得容易得多。这里有一个简单的例子来说明它是如何工作的。

<a href="#" data-affiliate="one" data-voteType="two">Click here</a>
$("a.vote").click(function(e){ 
    var affiliate = $(this).data('affiliate');
    var voteType =  $(this).data('voteType');
    // do your ajax call here 
    e.preventDefault(); 
}); 

代替-

var results = regex.exec( window.location.href );

could you do -

var results = regex.exec($("a.vote").attr('href'));

和解析变量直接从您的链接?