js分页查询怎么实现
原创JS分页查询实现
在Web开发中,分页查询是处理大量数据时常用的一种技术,它可以避免一次性加载过多数据促使的性能问题,同时也提升了用户体验。下面将介绍怎样使用JavaScript(结合Ajax)实现一个易懂的分页查询功能。
首先,我们需要在HTML中创建一个基本的分页结构,包括显示数据的表格和分页按钮。
<div id="pagination">
<table id="data-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div id="page-buttons">
<button id="prev-page">Prev</button>
<button id="next-page">Next</button>
</div>
</div>
接下来,我们使用JavaScript来处理分页逻辑。这里我们假设每页显示10条数据。
const itemsPerPage = 10;
let currentPage = 1;
let totalItems = 0;
let items = [];
// 模拟从服务器获取数据的函数
function fetchData(page, callback) {
// 在实际应用中,这里会是一个Ajax请求
// 假设我们从一个数组中获取数据,每页10条
const startIndex = (page - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
const pageItems = items.slice(startIndex, endIndex);
callback(pageItems);
}
// 初始化数据
function init() {
// 假设我们有100条数据
items = Array.from({length: 100}, (_, i) => ({id: i + 1, name: `Item ${i + 1}`, age: 25 + i}));
fetchData(currentPage, displayItems);
}
// 显示数据
function displayItems(items) {
const tbody = document.getElementById('data-table').getElementsByTagName('tbody')[0];
tbody.innerHTML = ''; // 清空表格内容
items.forEach(item => {
const row = document.createElement('tr');
row.innerHTML = `
<td>${item.id}</td>
<td>${item.name}</td>
<td>${item.age}</td>
`;
tbody.appendChild(row);
});
// 更新分页按钮状态
updatePageButtons();
}
// 更新分页按钮状态
function updatePageButtons() {
const prevPageButton = document.getElementById('prev-page');
const nextPageButton = document.getElementById('next-page');
prevPageButton.disabled = currentPage === 1;
nextPageButton.disabled = currentPage * itemsPerPage >= totalItems;
prevPageButton.addEventListener('click', () => {
if (currentPage > 1) {
currentPage--;
fetchData(currentPage, displayItems);
}
});
nextPageButton.addEventListener('click', () => {
if (currentPage * itemsPerPage < totalItems) {
currentPage++;
fetchData(currentPage, displayItems);
}
});
}
init();
这个例子中,我们使用了易懂的JavaScript逻辑来处理分页,包括获取数据、显示数据以及处理分页按钮的点击事件。在实际应用中,获取数据的部分通常会使用Ajax或Fetch API来从服务器异步获取数据。