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

请求为Laravel无限滚动脚本添加beforeSend加载效果

Laravel无限滚动添加加载提示解决方案

步骤1:在视图中添加加载提示元素

在你的列表容器下方,添加一个默认隐藏的加载提示元素,用来展示加载状态:

<!-- 列表内容容器 -->
<div class="data-container">
    @foreach($records as $record)
        <!-- 你的内容项模板 -->
        <div class="record-item">{{ $record->title }}</div>
    @endforeach
</div>

<!-- 加载提示元素 -->
<div class="ajax-load text-center py-4" style="display: none;">
    <span>加载中...</span>
</div>

步骤2:修改JavaScript代码控制加载状态

调整你的无限滚动JS逻辑,在发起请求前显示加载提示,请求完成(成功/失败)后隐藏,同时避免重复请求:

let currentPage = 1;
const triggerOffset = 100; // 距离页面底部多少像素触发加载

$(window).scroll(function() {
    const isNearBottom = $(window).scrollTop() + $(window).height() >= $(document).height() - triggerOffset;
    const isLoading = $('.ajax-load').is(':visible');

    // 滚动到底部且未在加载时,发起分页请求
    if (isNearBottom && !isLoading) {
        currentPage++;
        // 显示加载提示
        $('.ajax-load').show();

        $.ajax({
            url: `/your-api-path?page=${currentPage}`, // 替换为你的分页接口地址
            method: 'GET',
            success: function(res) {
                if (!res.html || res.html.trim() === '') {
                    // 无更多数据时更新提示文本
                    $('.ajax-load').html('<span>已加载全部内容</span>');
                    return;
                }
                // 隐藏提示并追加新内容
                $('.ajax-load').hide();
                $('.data-container').append(res.html);
            },
            error: function() {
                // 请求失败时隐藏提示,可按需添加错误提示
                $('.ajax-load').hide();
                alert('加载失败,请稍后重试');
            }
        });
    }
});

关键细节说明

  • 防重复请求:通过判断.ajax-load的可见状态,避免滚动时多次触发请求
  • 状态全流程控制:请求发起前显示提示,请求完成后(无论成功/失败)隐藏提示,无数据时更新提示文本
  • 样式自定义:可以给.ajax-load添加CSS动画(比如旋转加载图标),替代纯文本提示

内容的提问来源于stack exchange,提问作者BOLIBICK

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 06:52:11