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

Laravel实现带自动刷新与分页递增的数据库仪表盘咨询

实现方案及步骤

一、整体架构思路

用Laravel后端处理数据分页逻辑,前端通过JavaScript管理每个数据表的页码状态、定时刷新,以及页码递增/回跳逻辑。前后端职责清晰,适合新手快速上手。

二、后端:Laravel分页实现

为每个数据表编写控制器方法,返回分页后的结构化数据。以四个示例模型(User/Order/Product/Log)为例:

// DashboardController.php 示例方法:获取用户分页数据
public function userData(Request $request)
{
    $page = $request->input('page', 1);
    $perPage = 10; // 自定义每页显示条数
    $users = User::orderBy('created_at', 'desc')->paginate($perPage, ['*'], 'page', $page);
    
    return response()->json([
        'data' => $users->items(),
        'current_page' => $users->currentPage(),
        'last_page' => $users->lastPage(),
    ]);
}

其他三个数据表的方法逻辑一致,仅需替换模型和查询条件。最后在routes/api.php注册对应API路由:

Route::get('/dashboard/user-data', [DashboardController::class, 'userData']);
Route::get('/dashboard/order-data', [DashboardController::class, 'orderData']);
Route::get('/dashboard/product-data', [DashboardController::class, 'productData']);
Route::get('/dashboard/log-data', [DashboardController::class, 'logData']);

三、前端:自动刷新与页码控制

1. Blade页面结构

在视图中为四个数据表分别设置独立容器,确保各表状态互不干扰:

<div class="table-group">
    <h3>用户列表</h3>
    <table id="user-table" class="table">
        <thead>
            <tr><th>ID</th><th>名称</th><th>创建时间</th></tr>
        </thead>
        <tbody id="user-table-body"></tbody>
    </table>
    <p>当前页码:<span id="user-current">1</span> / <span id="user-last">1</span></p>
</div>

<!-- 订单/商品/日志表格结构完全一致,仅需替换ID前缀:order- / product- / log- -->

2. JavaScript核心逻辑

用原生JS编写通用刷新函数,维护每个表的独立页码状态:

// 配置每个数据表的核心参数
const tableConfigs = [
    {
        tableBodyId: 'user-table-body',
        currentPageId: 'user-current',
        lastPageId: 'user-last',
        apiUrl: '/dashboard/user-data',
        currentPage: 1,
        lastPage: 1
    },
    {
        tableBodyId: 'order-table-body',
        currentPageId: 'order-current',
        lastPageId: 'order-last',
        apiUrl: '/dashboard/order-data',
        currentPage: 1,
        lastPage: 1
    },
    // 商品、日志表的配置同上
];

// 刷新单个数据表的函数
function refreshSingleTable(config) {
    // 携带CSRF令牌发送请求
    fetch(`${config.apiUrl}?page=${config.currentPage}`, {
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
        }
    })
    .then(res => res.json())
    .then(data => {
        // 更新表格内容
        const tbody = document.getElementById(config.tableBodyId);
        tbody.innerHTML = '';
        data.data.forEach(item => {
            const row = document.createElement('tr');
            row.innerHTML = `<td>${item.id}</td><td>${item.name}</td><td>${item.created_at}</td>`;
            tbody.appendChild(row);
        });
        
        // 更新页码状态
        config.currentPage = data.current_page;
        config.lastPage = data.last_page;
        document.getElementById(config.currentPageId).textContent = config.currentPage;
        document.getElementById(config.lastPageId).textContent = config.lastPage;
        
        // 页码递增/回跳逻辑
        config.currentPage = config.currentPage < config.lastPage ? config.currentPage + 1 : 1;
    })
    .catch(err => console.error('加载失败:', err));
}

// 初始化仪表盘并设置定时刷新
function initDashboard() {
    // 首次加载所有表格
    tableConfigs.forEach(config => refreshSingleTable(config));
    
    // 每10秒自动刷新一次
    setInterval(() => {
        tableConfigs.forEach(config => refreshSingleTable(config));
    }, 10000);
}

// 页面加载完成后启动
document.addEventListener('DOMContentLoaded', initDashboard);

3. 简化版(jQuery)

如果新手对原生JS不熟悉,可改用jQuery实现,代码更简洁:

function refreshSingleTable(config) {
    $.ajax({
        url: config.apiUrl,
        data: { page: config.currentPage },
        success: function(data) {
            $('#' + config.tableBodyId).empty();
            $.each(data.data, function(i, item) {
                const row = `<tr><td>${item.id}</td><td>${item.name}</td><td>${item.created_at}</td></tr>`;
                $('#' + config.tableBodyId).append(row);
            });
            
            config.currentPage = data.current_page;
            config.lastPage = data.last_page;
            $('#' + config.currentPageId).text(config.currentPage);
            $('#' + config.lastPageId).text(config.lastPage);
            
            config.currentPage = config.currentPage < config.lastPage ? config.currentPage + 1 : 1;
        }
    });
}

四、注意事项

  • 确保Blade模板中已添加CSRF令牌元标签:<meta name="csrf-token" content="{{ csrf_token() }}">,否则请求会被Laravel拦截。
  • 可根据需求调整控制器中$perPage的值,修改每页显示条数。
  • 数据量较大时,建议在查询中指定需要的字段(如select('id', 'name', 'created_at')),避免性能浪费。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 00:15:05