如何使用 base javascript 将分页引入通过 XMLhttprequest 检索的 JSON 数据?

How to introduce pagination using basic javascript to a JSON data retrieved through XMLhttp request?

我正在使用 XMLHttp 请求检索 JSON 数据,我将它们放在 table 中。我想引入分页,这样每个页面只会显示 5 组数据,仅使用 javascript 的基础知识。我尝试使用无序列表然后点击,我尝试使用按钮,但我没有得到想要的结果。我对此真的很陌生,而且我没有想法。请提供一些关于如何实现所需输出的见解。

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);
  console.log(data);

  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);

  var i = 0;
  for (let num = 1; num <= 20; num++) {
    for (let x = i * 5; x < ((i + 1) * 5); x++) {
      let k = data[x];
      foo(k.id, k.name, k.email, x);
    }
    i++
  }


  function foo(id, name, email, rownum) {
    var td1 = document.createElement('td');
    var td2 = document.createElement('td');
    var td3 = document.createElement('td');
    td1.innerHTML = id
    td2.innerHTML = name;
    td3.innerHTML = email;
    var tr = document.createElement('tr');
    if (rownum % 2 === 0) tr.setAttribute('style', 'background-color:#d3d3d3');
    tr.append(td1, td2, td3);
    tbody.append(tr);
    table.append(tbody);
  }
  document.body.append(table);

}

从你的 OP 来看,我不太确定你 运行 遇到了什么问题。您需要跟踪 table 结果,以便用户向前和向后导航。如何跟踪结果取决于您,但我在下面创建了一个片段来展示示例。我假设您的数据结构为对象数组。这个例子应该让你开始。

基本上,代码通过将索引保存在 table 的数据属性中来跟踪显示了哪些记录。然后,当用户发送导航页面的命令时,代码将使用这些索引号检索下一组或上一组记录以显示在 table.

const table = document.querySelector('table');
const theadRow = table.querySelector('thead tr')
const tbody = table.querySelector('tbody')
const navigation = document.querySelector('.navigation');
const myDataArray = [{
        id: '001',
        name: "bob",
        email: 'nothing@aol.com'
    },
    {
        id: '002',
        name: "susy",
        email: 'nothing@aol.com'
    },
    {
        id: '003',
        name: "jim",
        email: 'nothing@aol.com'
    },
    {
        id: '004',
        name: "anny",
        email: 'nothing@aol.com'
    },
    {
        id: '005',
        name: "greg",
        email: 'nothing@aol.com'
    },
    {
        id: '006',
        name: "pepe",
        email: 'nothing@aol.com'
    },
    {
        id: '007',
        name: "mickey",
        email: 'nothing@aol.com'
    },
]

const paginationConfig = {
    resultsPerPage: 2,
}
// set default page start
table.dataset.recordStart = 0
table.dataset.recordEnd = paginationConfig.resultsPerPage - 1

displayDefaultTablePage(myDataArray)

function displayDefaultTablePage(data) {
    let currentRecordStart = parseInt(table.dataset.recordStart)
    let currentRecordEnd = parseInt(table.dataset.recordEnd)

    let headerLabels = Object.keys(data[0])
    for (let i = 0; i < headerLabels.length; i++) {
        let th = document.createElement('th')
        th.textContent = headerLabels[i]
        theadRow.append(th)
    }
    let recordsToDisplay = data.slice(currentRecordStart, currentRecordEnd + 1)
    createTbodyCells(recordsToDisplay)
}

// listen for user commands
navigation.addEventListener('click', (e) => {
    if (e.target.matches('.next')) {
        changePage('next')
    } else {
        changePage('prev')
    }
})

// determine direction and initialize the page change
function changePage(direction) {
    let currentRecordStart = parseInt(table.dataset.recordStart)
    let currentRecordEnd = parseInt(table.dataset.recordEnd)

    if (direction === 'next') {
        if(currentRecordEnd+1>myDataArray.length){
            return
        }
        let newStart = currentRecordEnd + 1
        let newEnd = newStart + paginationConfig.resultsPerPage - 1

        table.dataset.recordStart = newStart
        table.dataset.recordEnd = newEnd
        let recordsToDisplay = myDataArray.slice(newStart, newEnd + 1)

        createTbodyCells(recordsToDisplay)
    } else if (direction === 'prev') {
        if(currentRecordStart==0){
            return
        }
        let newEnd = currentRecordStart - 1
        let newStart = newEnd - paginationConfig.resultsPerPage+1

        table.dataset.recordStart = newStart
        table.dataset.recordEnd = newEnd
        let recordsToDisplay = myDataArray.slice(newStart, newEnd + 1)

        createTbodyCells(recordsToDisplay)
    } else {
        return
    }

}

// add records to DOM
function createTbodyCells(records) {
    tbody.textContent = ''
    for (let i = 0; i < records.length; i++) {
        let record = records[i]
        let tr = document.createElement('tr')
        for (const key in record) {
            if (Object.hasOwnProperty.call(record, key)) {
                let td = document.createElement('td')
                td.textContent = record[key]
                tr.append(td)
            }
        }
        tbody.append(tr)
    }
}
body {
    background-color: rgb(235, 235, 235);
}
th{
    background-color: black;
    color: white;
}
td{
    border: 1px solid black;
    padding: .5rem;
}
button{
    border: none;
    padding: .5rem;
    background-color: rgb(13, 118, 179);
    color: white;
}
.container{
    width: fit-content;
    margin: auto;
}
.navigation{
   width: fit-content;
   margin: auto;
}
  <div class="container">
        <table data-record-start="0" data-record-end="">
            <thead>
                <tr>
    
                </tr>
            </thead>
            <tbody>
                
            </tbody>
        </table>
    
        <div class="navigation">
            <button class="prev">Prev</button>
            <button class="next">Next</button>
        </div>
    </div>

我假设您正在获取对象数组。

这是一个分页函数 (vanilla js),它将数组转换为 -> 数组数组

const paginate = (data) => {
    const DATA_PER_PAGE = 5;
    const TOTAL_USER_COUNT = data.length;
    const PAGE_COUNT = Math.ceil(TOTAL_USER_COUNT / DATA_PER_PAGE);

    const paginatedData = Array.from({ length: PAGE_COUNT }, (_, index) => {
        const start = index * DATA_PER_PAGE;
        return data.slice(start, start + DATA_PER_PAGE);
    });

    return paginatedData;
};

现在,这个数组的长度是'number of pages'。使用此长度,您可以动态生成按钮。添加事件侦听器(我将使用事件委托和索引(或者可能是数据 ID))并访问您需要的数据(这意味着如果单击的按钮是索引 0,则访问此数组数组的第 0 个索引)。