php防止重复提交 ajax,php – 防止堆叠AJAX请求

这篇博客讨论了在实现类似Twitter的滚动加载新帖子功能时遇到的问题,即当用户滚动速度过快,jQuery AJAX请求可能发送多次,导致内容重复。作者提出了一种解决方案,通过设置一个变量`runningRequest`来跟踪是否已有请求在运行,以此避免并发请求,从而防止双帖问题的发生。
摘要由CSDN通过智能技术生成

我遇到了一个我似乎无法解决的问题.

我目前正在实现一个类似于Twitter使用的AJAX功能 – 在滚动时获取新帖子.

jQuery看起来像这样:

$(window).scroll(function(){

if($(window).scrollTop() == $(document).height() - $(window).height()){

$('div#ajaxloader').show();

$.ajax({

url: "loader.php?lastid=" + $(".container:last").attr("id"),

success: function(html){

if(html){

$("#main").append(html);

$('div#ajaxloader').hide();

}else{

$('div#ajaxloader').html('No more posts to show.');

}

}

});

}

});

现在问题;如果用户滚动得非常快并且数据库正在快速完成工作 – jQuery似乎无法足够快地发送正确的id作为查询 – 这导致双帖.

任何人都知道如何防止这种情况?

解决方法:

试试这个:

var runningRequest = 0;

$(window).scroll(function(){

if(runningRequest <1){

if($(window).scrollTop() == $(document).height() - $(window).height()){

runningRequest++;

$('div#ajaxloader').show();

$.ajax({

url: "loader.php?lastid=" + $(".container:last").attr("id"),

success: function(html){

runningRequest--;

if(html){

$("#main").append(html);

$('div#ajaxloader').hide();

}else{

$('div#ajaxloader').html('No more posts to show.');

}

}

error: function(){runningRequest--;}

});

}

}

});

标签:jquery,php,javascript

来源: https://codeday.me/bug/20190531/1187977.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值