[英]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.