我目前正在开发一些 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/