[英]Get URL parameters from text link and post to AJAX call
我目前正在研究一些允许用户通过文本链接进行AJAX调用的jQuery。 这没问题,但是文本链接有我需要发送给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);
这段代码的问题是我无法在执行函数之前提交链接以在网址中放置任何参数,从而导致空的affiliate和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 );
你能做什么 -
var results = regex.exec($("a.vote").attr('href'));
并直接从您的链接解析变量?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.