简体   繁体   English

如何将使用基本 javascript 的分页引入通过 XMLhttp 请求检索到的 JSON 数据?

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

I am retrieving a JSON data using XMLHttp request and I have them in a table.我正在使用 XMLHttp 请求检索 JSON 数据,并将它们放在一个表中。 I want to introduce pagination such that each page will only display 5 sets of data using only the very basics of javascript. I tried using an unordered list and then onclick, I tried using buttons, but I am not getting the desired result.我想引入分页,这样每个页面将仅使用 javascript 的最基本知识仅显示 5 组数据。我尝试使用无序列表,然后使用 onclick,我尝试使用按钮,但我没有得到想要的结果。 I am really new to this and I am out of ideas.我对此真的很陌生,而且我没有想法。 Kindly provide some insight on how to achieve the desired output.请提供一些关于如何实现所需的 output 的见解。

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

}

From your OP, I 'm not exactly sure what issue you are running into.从您的 OP 来看,我不确定您遇到了什么问题。 You'll need to track your table results in order for a user to navigate forward and backwards.您需要跟踪表格结果,以便用户向前和向后导航。 How you track your results is up to you, but I created a snippet below showcasing an example.如何跟踪结果取决于您,但我在下面创建了一个片段来展示示例。 I assume your data is structured as an array of objects.我假设您的数据结构为对象数组。 This example should get you started.这个例子应该让你开始。

Basically, the code keeps track of which records are displayed by saving their index within the data attribute of the table.基本上,代码通过将索引保存在表的数据属性中来跟踪显示了哪些记录。 Then, when a user sends a command to navigate the page, the code will use these index numbers to retrieve the next or previous set of records for displaying on the 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>

I assume you're getting an array of objects.我假设你得到了一组对象。

Here is a paginate function (vanilla js), which converts an array to -> an array of arrays这是一个分页 function(vanilla js),它将数组转换为 -> arrays 的数组

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

Now, the length of this array is the 'number of pages'.现在,这个数组的长度就是“页数”。 using this length you can dynamically generate buttons.使用此长度,您可以动态生成按钮。 Add event listener (I'd use event delegation and indexes(or maybe data-id)) and access the data you need (meaning that if the button clicked is index 0, then access 0th index on this array of arrays).添加事件侦听器(我将使用事件委托和索引(或者可能是数据 ID))并访问您需要的数据(这意味着如果单击的按钮是索引 0,则访问此数组数组的第 0 个索引)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM