简体   繁体   中英

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. 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. I am really new to this and I am out of ideas. Kindly provide some insight on how to achieve the desired 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. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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