如何使用Express与EJS实现海量用户数组数据的分页展示功能
Express + EJS 实现数组分页及页码切换方案
核心逻辑
分页依赖4个核心参数:当前页码currentPage、每页展示条数pageSize、总数据量total、总页数totalPages。后端从请求参数中获取当前页码,对用户数组做切片得到当前页数据,将所有分页参数传递给EJS模板渲染即可。
1. 后端Express实现
首先安装所需依赖:npm install express ejs
服务端代码示例:
const express = require('express'); const app = express(); // 配置EJS模板引擎 app.set('view engine', 'ejs'); app.set('views', './views'); // 模板文件默认放在项目根目录的views文件夹下 // 替换为你的实际用户数据数组 const userArray = Array.from({length: 125}, (_, index) => ({ id: index + 1, name: `用户${index + 1}`, email: `user${index + 1}@example.com` })); // 用户列表分页路由 app.get('/users', (req, res) => { // 处理当前页码的非法值 let currentPage = parseInt(req.query.page) || 1; const pageSize = 10; // 自定义每页展示条数 const total = userArray.length; const totalPages = Math.ceil(total / pageSize); // 页码边界校正:避免页码小于1或大于总页数 currentPage = Math.max(1, Math.min(currentPage, totalPages)); // 数组切片获取当前页数据 const startIndex = (currentPage - 1) * pageSize; const currentPageData = userArray.slice(startIndex, startIndex + pageSize); // 传递数据到EJS模板 res.render('users', { currentPageData, currentPage, totalPages, total }); }); app.listen(3000, () => { console.log('服务已启动,访问地址:http://localhost:3000/users'); });
2. 前端EJS模板实现(含页码按钮)
在项目views文件夹下新建users.ejs文件,内容如下:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>用户列表</title> <style> .user-item { padding: 10px 0; border-bottom: 1px solid #eee; } .pagination { margin-top: 20px; } .pagination a, .pagination span { display: inline-block; padding: 5px 12px; margin: 0 2px; border: 1px solid #ddd; border-radius: 2px; text-decoration: none; color: #333; } .pagination .active { background: #0d6efd; color: #fff; border-color: #0d6efd; } .pagination .disabled { color: #999; cursor: not-allowed; } </style> </head> <body> <h1>用户列表</h1> <p>总数据量:<%= total %> 条,当前第 <%= currentPage %> / <%= totalPages %> 页</p> <!-- 当前页用户数据展示 --> <div class="user-list"> <% currentPageData.forEach(user => { %> <div class="user-item"> ID:<%= user.id %> | 用户名:<%= user.name %> | 邮箱:<%= user.email %> </div> <% }) %> </div> <!-- 底部分页按钮区域 --> <div class="pagination"> <!-- 上一页按钮 --> <% if(currentPage > 1) { %> <a href="/users?page=<%= currentPage - 1 %>">上一页</a> <% } else { %> <span class="disabled">上一页</span> <% } %> <!-- 中间页码 --> <% for(let i = 1; i <= totalPages; i++) { %> <% if(i === currentPage) { %> <span class="active"><%= i %></span> <% } else { %> <a href="/users?page=<%= i %>"><%= i %></a> <% } %> <% } %> <!-- 下一页按钮 --> <% if(currentPage < totalPages) { %> <a href="/users?page=<%= currentPage + 1 %>">下一页</a> <% } else { %> <span class="disabled">下一页</span> <% } %> </div> </body> </html>
优化提示
如果总页数超过20页,可修改中间页码的渲染逻辑,仅展示当前页前后3-5个页码,避免底部页码区域过长。
内容的提问来源于stack exchange,提问作者user14257052
相关产品推荐
相关产品推荐

