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

如何使用原生JavaScript为XMLHttpRequest获取的JSON数据实现分页

原生JavaScript实现表格分页方案

核心实现思路

  • 维护两个核心状态:currentPage(当前页码,默认值1)、pageSize(每页展示条数,固定为5)
  • 封装独立的表格渲染函数:每次切换页码时清空原有表格内容,只渲染当前页对应区间的数据
  • 封装分页按钮渲染函数:根据总数据量计算总页数,为每个分页按钮绑定点击事件,切换页码后重新渲染表格
  • 处理边界逻辑:第一页禁用上一页按钮,最后一页禁用下一页按钮

完整可运行代码

var request = new XMLHttpRequest();
request.open('GET', 'https://raw.githubusercontent.com/Rajavasanthan/jsondata/master/pagenation.json', true);
request.send();

request.onload = function() {
  var data = JSON.parse(request.response);
  // 分页核心配置
  const pageSize = 5;
  let currentPage = 1;
  const totalPages = Math.ceil(data.length / pageSize);

  // 创建表格基础结构
  var table = document.createElement('table');
  table.setAttribute('class', 'table');
  var thead = document.createElement('thead');
  thead.setAttribute('class', 'thead-dark')
  var tr = document.createElement('tr');
  var tbody = document.createElement('tbody');

  var th1 = document.createElement('th')
  th1.innerHTML = 'id'
  var th2 = document.createElement('th');
  th2.innerHTML = 'Name'
  var th3 = document.createElement('th');
  th3.innerHTML = 'Email';

  tr.append(th1, th2, th3);
  thead.append(tr);
  table.append(thead, tbody);
  document.body.append(table);

  // 创建分页按钮容器
  const paginationWrapper = document.createElement('div');
  paginationWrapper.style.marginTop = '12px';
  document.body.append(paginationWrapper);

  // 渲染表格函数
  function renderTable() {
    // 清空原有表格内容
    tbody.innerHTML = '';
    // 计算当前页数据区间
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = currentPage * pageSize;
    const currentPageData = data.slice(startIndex, endIndex);
    // 渲染当前页数据
    currentPageData.forEach((item, index) => {
      const tr = document.createElement('tr');
      // 全局行号,用于奇偶行变色
      const globalRowIndex = startIndex + index;
      if (globalRowIndex % 2 === 0) tr.style.backgroundColor = '#d3d3d3';
      tr.innerHTML = `
        <td>${item.id}</td>
        <td>${item.name}</td>
        <td>${item.email}</td>
      `;
      tbody.append(tr);
    });
  }

  // 渲染分页按钮函数
  function renderPagination() {
    paginationWrapper.innerHTML = '';
    // 上一页按钮
    const prevBtn = document.createElement('button');
    prevBtn.textContent = '上一页';
    prevBtn.disabled = currentPage === 1;
    prevBtn.style.marginRight = '8px';
    prevBtn.addEventListener('click', () => {
      if (currentPage > 1) {
        currentPage--;
        renderTable();
        renderPagination();
      }
    });
    paginationWrapper.append(prevBtn);

    // 页码按钮
    for (let i = 1; i <= totalPages; i++) {
      const pageBtn = document.createElement('button');
      pageBtn.textContent = i;
      pageBtn.style.marginRight = '8px';
      if (i === currentPage) {
        pageBtn.style.backgroundColor = '#165DFF';
        pageBtn.style.color = '#fff';
      }
      pageBtn.addEventListener('click', () => {
        currentPage = i;
        renderTable();
        renderPagination();
      });
      paginationWrapper.append(pageBtn);
    }

    // 下一页按钮
    const nextBtn = document.createElement('button');
    nextBtn.textContent = '下一页';
    nextBtn.disabled = currentPage === totalPages;
    nextBtn.addEventListener('click', () => {
      if (currentPage < totalPages) {
        currentPage++;
        renderTable();
        renderPagination();
      }
    });
    paginationWrapper.append(nextBtn);
  }

  // 初始化渲染
  renderTable();
  renderPagination();
}

代码说明

  • 移除了原有冗余的双重循环逻辑,改用slice方法切割当前页需要的数据,性能更高
  • 表格渲染和分页渲染逻辑完全解耦,每次切换页码只需要重新调用两个渲染函数即可
  • 分页按钮做了样式区分,当前页按钮高亮展示,边界状态下对应按钮自动禁用
  • 保留了原有奇偶行变色的样式逻辑,计算全局行号保证样式一致性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 12:39:00