javascript - 从文本链接获取 URL 参数并发布到 AJAX 调用

标签 javascript ajax jquery

我目前正在开发一些 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(); 
}); 

关于javascript - 从文本链接获取 URL 参数并发布到 AJAX 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8054071/

相关文章:

javascript - WordPress Material 设计问题

ajax - 使用 AJAX (jQuery) 加载日期在 div 内无限滚动

c# - 通过 css 或 jquery/c# 设置图像大小

javascript - 如何使用javascript/jquery获取隐藏字段的值

javascript - jquery 无限循环(移动一个 div 位置)

javascript - JavaScript 中的正则表达式

javascript - jQuery post 将错误的输入值传递给 PHP

javascript - amCharts 中的实时图表完全刷新

javascript - 可点击的数据表行

php - 保留像 é 这样的特殊字符