我很难弄清楚如何避免对我的无限滚动 javascript 代码进行重复的 ajax 调用。 它主要工作,但有时我有 2 或 3 次相同的 ajax 页面调用导致某种循环。 如何避免这种情况? 谢谢
//infiniteScroll
var currentPage = 1;
var intervalID = -1000;
var scroll = false;
$('document').ready(function(){
if ( scroll == true) {
if (window.location.pathname == "/" && window.location.search == "" && $('#items_container').length > 0) {
$('.pagination').hide();
intervalID = setInterval(checkScroll, 300);
}
};
})
function checkScroll() {
if (nearBottomOfPage()) {
currentPage++;
jQuery.ajax('?page=' + currentPage, {asynchronous:true, evalScripts:true, method:'get',
beforeSend: function(){
var scroll = false;
$('.spinner').show();
},
success: function(data, textStatus, jqXHR) {
$('.spinner').hide();
$('#items_container').append(jQuery(data).find('#items_container').html());
var scroll = true;
if(typeof jQuery(data).find('.item').html() == 'undefined' || jQuery(data).find('.item').html().trim().length == 0 || currentPage == 10){
clearInterval(intervalID);
}
},});
}
}
}
function nearBottomOfPage() {
return scrollDistanceFromBottom() < 450;
}
function scrollDistanceFromBottom(argument) {
return pageHeight() - (window.pageYOffset + self.innerHeight);
}
function pageHeight() {
return Math.max(document.body.scrollHeight, document.body.offsetHeight);
}
最佳答案
checkScroll 函数似乎每 300 毫秒被调用一次,AJAX 请求可能需要比这更长的时间。
我看到你有滚动变量,但你只是在初始文档加载时检查它的值,这不会影响计时器。
我建议看看监听滚动事件而不是创建计时器:jQuery docs .然后,您可以执行类似以下操作来防止运行两个 ajax 调用:
var ajaxRunning = false;
function checkScroll() {
if (!ajaxRunning && nearBottomOfPage()) {
currentPage++;
ajaxRunning = true;
jQuery.ajax('?page=' + currentPage, {asynchronous:true, evalScripts:true, method:'get',
beforeSend: function(){
$('.spinner').show();
},
success: function(data, textStatus, jqXHR) {
$('.spinner').hide();
$('#items_container').append(jQuery(data).find('#items_container').html());
if(typeof jQuery(data).find('.item').html() == 'undefined' || jQuery(data).find('.item').html().trim().length == 0 || currentPage == 10){
clearInterval(intervalID);
},
complete: function() {
ajaxRunning = false;
}
},});
}
}
关于javascript - 无限滚动重复ajax调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23012980/