我有一个有n个选项卡的门户,每当访问者单击特定选项卡时,就会创建一个AJAX请求。后端的PHP脚本将一条记录插入到一个表中,该表跟踪单击的时间和单击的选项卡的名称。
当访问者连续多次单击同一个选项卡时,所有AJAX请求都成功了。假设我单击"自动化"选项卡5次,那么5个AJAX请求成功,5条记录被插入。我需要将请求限制为只有一个,如果访问者重复并快速单击选项卡的3秒间隔。怎么做呢?
这是我的jQuery AJAX代码:$.ajax({
url : "pushTelemetry.php",
cache : false,
data : ({
DshBrdName : strFullDashBoardName,
DshBrdID : currentDashboard,
r : Math.random()
}),
success : function(data, textStatus, jQxhr){
//alert(textStatus);
},
error : function(jqXHR, textStatus, errorThrown){
//alert(textStatus);
alert(errorThrown);
},
type : "POST"
});
这样做的目的是表明只有在没有AJAX调用的情况下才应该进行AJAX调用。在这里,我使用按钮上的一个额外类来表示它,该类触发ajax调用。
执行如下命令:
$(selector).on("click",function () {
if ($(this).is(".pendingResult") { return; }
$(this).addClass("pendingResult");
var finally = $.proxy(function () { $(this).removeClass("pendingResult"); }, this);
$.ajax({
url : "pushTelemetry.php",
cache : false,
data : ({
DshBrdName : strFullDashBoardName,
DshBrdID : currentDashboard,
r : Math.random()
}),
success : function(data, textStatus, jQxhr){
//alert(textStatus);
},
error : function(jqXHR, textStatus, errorThrown){
//alert(textStatus);
alert(errorThrown);
},
type : "POST",
complete : finally
});
});
进一步的细节:
JQuery AJAX调用可以在成功或错误中终止,但是无论何时发生这两种情况,如果指定,则调用"complete"函数,这类似于try-catch-finally块中的finally
代码。然而,这个"完成"函数的作用域是窗口,而不是触发AJAX调用的元素,因此,如果您需要以某种方式将单击的元素传递给"完成"函数。幸运的是,JQuery有一个内置的方法来做到这一点,使用proxy
方法。此方法接受回调和范围/元素,并确保回调中的"This"对象引用指定的范围元素。这类似于内置的JavaScript方法bind
,我在这里使用代理的原因是绑定是较新的,在IE 8中不支持,有些人可能仍然试图支持(出于某种原因)。
您可以禁用选项卡上的单击,直到您从服务器获得响应。
var clickAllowed = true;
$('#tab').on('click', function() {
if(clickAllowed) {
clickAllowed = false;
$.ajax({
url : "pushTelemetry.php",
cache : false,
data : ({
DshBrdName : strFullDashBoardName,
DshBrdID : currentDashboard,
r : Math.random()
}),
success : function(data, textStatus, jQxhr){
//alert(textStatus);
clickAllowed = true;
},
error : function(jqXHR, textStatus, errorThrown){
//alert(textStatus);
alert(errorThrown);
clickAllowed = true;
},
type : "POST"
});
}
});