You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

scroll函数重复触发且未等待数据库返回数据问题求助

解决jQuery滚动加载时多次触发AJAX的问题

你的问题核心是scroll事件会在滚动过程中频繁触发,而且没有状态控制,导致AJAX请求还未完成就重复发起新请求。可以通过添加一个「加载锁」来解决,同时也能避免不必要的重复请求。

修改后的代码如下:

$(document).ready(function(){
    // 新增加载状态标记,初始为未加载
    var isLoading = false;

    $(window).scroll(function(){
        var lastID = $('.load-more').attr('lastID');
        
        // 先判断是否正在加载,若正在加载则直接返回
        if(isLoading) return;

        if(($('#postList').height() <= $(window).scrollTop() + $(window).height())&& (lastID != 0)){
            isLoading = true; // 请求前标记为正在加载
            $.ajax({
                type:'POST',
                url:'getData.php',
                data:'id='+lastID,
                beforeSend:function(){
                    $('.load-more').show();
                },
                success:function(html){
                    $('.load-more').remove();
                    $('#postList').append(html);
                },
                complete:function(){
                    // 请求完成(无论成功/失败)都重置加载状态
                    isLoading = false;
                }
            });
        }
    });
});

关键改动说明:

  • 新增isLoading变量作为加载锁,初始值为false,表示当前没有正在进行的请求。
  • 在scroll事件触发时,先检查isLoading,如果是true直接跳过,避免重复发起请求。
  • 发起AJAX前将isLoading设为true,标记当前正在加载。
  • 使用complete回调(不管请求成功还是失败都会执行)重置isLoading为false,确保下一次滚动能正常触发请求。

如果想进一步优化滚动事件的触发频率(减少不必要的scroll事件执行),可以加入节流函数:

$(document).ready(function(){
    var isLoading = false;
    // 节流函数,控制scroll事件每200ms只执行一次
    function throttle(func, delay) {
        var timer = null;
        return function() {
            var context = this;
            var args = arguments;
            if (!timer) {
                timer = setTimeout(function() {
                    func.apply(context, args);
                    timer = null;
                }, delay);
            }
        }
    }

    $(window).scroll(throttle(function(){
        var lastID = $('.load-more').attr('lastID');
        
        if(isLoading) return;

        if(($('#postList').height() <= $(window).scrollTop() + $(window).height())&& (lastID != 0)){
            isLoading = true;
            $.ajax({
                type:'POST',
                url:'getData.php',
                data:'id='+lastID,
                beforeSend:function(){
                    $('.load-more').show();
                },
                success:function(html){
                    $('.load-more').remove();
                    $('#postList').append(html);
                },
                complete:function(){
                    isLoading = false;
                }
            });
        }
    }, 200)); // 200ms的节流间隔,可根据需求调整
});

这个节流函数能让scroll事件在滚动过程中每隔200ms才执行一次,进一步减少不必要的逻辑判断和请求触发。

内容的提问来源于stack exchange,提问作者Snake-hh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 07:07:20