我遇到了一个我似乎无法解决的问题。
我目前正在实现一个类似于 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--;}
});
}
}
});
关于php - 防止 AJAX 请求的堆叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5512946/