我有一个显示一些新闻的网页,点击时显示对服务器进行 AJAX 调用的旧新闻。
问题是,如果人们点击太快,请求会完成两次,因此,我会收到 2 个相等的响应。
-
#mas-noticias-footer 是显示旧新闻的按钮的 ID
-
.noticias-list 是分配给每个新事物的类,使用 .length 我得到显示的新闻数量,并将该数字发布到 PHP 文件中使用 LIMIT(numItems,3) 进行 SQL 查询(我一次收到 3 条新闻)。
-
#noticias 显示是包含新闻的 UL
这是代码
$(document).ready(function() {
$("#mas-noticias-footer").on('click',function() {
var numItems = $('.noticias-list').length;
$.ajax({
type: "POST",
url: "mas-noticias.php",
data: "num-noticias="+numItems,
success: function(data) {
$('#noticias-display').append(data);
}
});
});
});
我已经尝试使用 off() 并在回调开始时解绑事件,以避免多次调用(有效),问题是当我在回调结束时使用 on() 委托事件时,我无法让它工作。
你不能方便地调用off
,然后调用on
期望绑定事件像这样返回,事件不存储在内存中。
但是,您可以在 DOM 中设置一个数据变量:
$("#mas-noticias-footer").on('click',function() {
var numItems = $('.noticias-list').length;
var isAjaxRunning = $(this).data('iar');
// check flag is set
if(typeof isAjaxRunning == 'undefined') $(this).data('iar', 'yes');
else if(isAjaxRunning == 'yes') return; // if still running, return
$.ajax({
type: "POST",
url: "mas-noticias.php",
data: "num-noticias="+numItems,
success: function(data) {
$('#noticias-display').append(data);
$(this).data('iar', 'no'); // after successful run, set to no
}
});
});
我不相信你真的想要在这里进行异步调用。设置async:false
或使用$.post()
而不是$.ajax()
。
$(document).ready(function() {
$("#mas-noticias-footer").on('click', getnews);
function getnews() {
$("#mas-noticias-footer").off('click', getnews);
var numItems = $('.noticias-list').length;
$.ajax({
type: "POST",
url: "mas-noticias.php",
data: "num-noticias="+numItems,
success: function(data) {
$('#noticias-display').append(data);
},
complete: function() {
$("#mas-noticias-footer").on('click', getnews);
}
});
}
});
如果将 on() 与委派一起使用,请确保以相同的方式使用 off()。
您是否尝试过禁用该按钮?
$(document).ready(function() {
$("#mas-noticias-footer").on('click',function() {
var self=this;
$(self).attr('disabled','disabled'); //<-Disable
var numItems = $('.noticias-list').length;
$.ajax({
type: "POST",
url: "mas-noticias.php",
data: "num-noticias="+numItems,
success: function(data) {
$('#noticias-display').append(data);
$(self).removeAttr('disabled');//<-Enable
}
});
});
这已经得到了回答,但是我已经使用$.unbind
并稍微分离了代码提出了一个解决方案
演示