$(window).scroll(function() 加载多次

问题描述 投票:0回答:1

我正在使用滚动功能,问题是它加载了很多次并且不等待数据库发出的新信息。

这是代码!

$(document).ready(function(){
$(window).scroll(function(){
    var lastID = $('.load-more').attr('lastID');
    
     if(($('#postList').height() <= $(window).scrollTop() + $(window).height())&& (lastID != 0)){
        $.ajax({
            type:'POST',
            url:'getData.php',
            data:'id='+lastID,
            beforeSend:function(){
                $('.load-more').show();             },
            success:function(html){
                $('.load-more').remove();
                $('#postList').append(html);
            }
        });
    }
});

});

希望您能帮助我,谢谢!

javascript php ajax function scroll
1个回答
0
投票

如果您只是想阻止 AJAX 请求在另一个 AJAX 请求正在运行时启动,请使用变量从滚动函数返回。在 AJAX 请求之前将其设置为 true,并在

always
处理程序中将其重置为 false:

var loading = false;
$(document).ready(function(){
    $(window).scroll(function(){
        if(loading)
            return;

        var lastID = $('.load-more').attr('lastID');
        
        if(($('#postList').height() <= $(window).scrollTop() + $(window).height())&& (lastID != 0)){
            loading = true;
            $.ajax({
                type:'POST',
                url:'getData.php',
                data:'id='+lastID,
                beforeSend:function(){
                    $('.load-more').show();             
                },
                success:function(html){
                    $('.load-more').remove();
                    $('#postList').append(html);
                },
                always: function() {
                    loading = false;
                }
            });
        }
    });
});

(未经测试)

正如 @ProfessorAbronsius 在评论中建议的那样:也看看 Intersection Observer API。似乎是一种更稳定的方法。

© www.soinside.com 2019 - 2024. All rights reserved.