[英]Get URL parameters from text link and post to AJAX call
I'm currently working on a bit of jQuery that will allow users to make an AJAX call from a text link. 我目前正在研究一些允许用户通过文本链接进行AJAX调用的jQuery。 This is no problem but the text link has parameters that I need to send to the AJAX request in order for it to execute properly.
这没问题,但是文本链接有我需要发送给AJAX请求的参数才能正确执行。
My text link looks something like this: 我的文字链接看起来像这样:
<a href="?affiliate=one&voteType=two">Click here</a>
Here is my jQuery: 这是我的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);
The trouble with this code is I can't submit the link to put any parameters in the url before the function is executed, resulting in empty affiliate and voteType vars. 这段代码的问题是我无法在执行函数之前提交链接以在网址中放置任何参数,从而导致空的affiliate和voteType变量。
Can anyone help? 有人可以帮忙吗?
A better approach would be to store the data you need in the data-*
attribute of the link. 更好的方法是将所需数据存储在链接的
data-*
属性中。 This would make it much easier to retrieve the corresponding data. 这将使检索相应数据变得更加容易。 Here's a simple example of how it would work.
这是一个如何工作的简单示例。
<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();
});
Instead of - 代替 -
var results = regex.exec( window.location.href );
could you do - 你能做什么 -
var results = regex.exec($("a.vote").attr('href'));
and parse the variables directly from your link? 并直接从您的链接解析变量?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.