【问题标题】:Implement Pagination in JavaScript with limit and offset使用限制和偏移在 JavaScript 中实现分页
【发布时间】:2022-08-19 01:22:18
【问题描述】:

我从 fetch api 调用中返回了大量数据。我想将显示的数据限制为每页 10 个,并在单击下一页按钮时返回更多数据。我该如何实施?

limit 设置为 10,offset 设置为 0。每页可以返回的最大数据为 150。


<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button class = B1 id=\"photos\">View photos</button>
<div id=\"showResults\"></div>
<div>
  <nav aria-label=\"Page navigation example\">
    <ul class=\"pagination\">
     
      <li class=\"page-item\">
        <button class=\"page-link\" id=\"nextButton\">Next</button>
      </li>
    </ul>
  </nav>
</div>

<script> 
let limit = 10;
let offset = 0;
const showPhoto = (key, value) => {
 const pre_x = document.createElement(\"pre\");
 const dt_x = document.createElement(\"dt\");
 const dd_x = document.createElement(\"dd\")
 dt_x.textContent = key;
 pre_x.appendChild(dt_x);

  {
      dd_x.textContent = value;
   }
   pre_x.appendChild(dd_x);
 return pre_x;
};

const structurePhotos = (obj) => {
 const dl = document.createElement(\"dl\");
 for (let k in obj) {
   let j = obj[k];
   if (typeof obj[k] === \"object\") {
     j = JSON.stringify(obj[k], null, 2);
   }
dl.appendChild(showPhoto(k, j));
  }
 return dl;
};


function getPhotos(url) {
 fetch(url)
   .then((res) => (res.ok ? res.json() : Promise.reject(res)))
   .then((data) => {

     if (Array.isArray(data)) {
       data.forEach((photo) => {
         showResults.append(
          structurePhotos(photo),
         );
       });
     } 
   })
   .catch(console.error);
}

const photos = document.getElementById(\"photos\");
photos.addEventListener(
 \"onclick\",
 getPhotos(`https://jsonplaceholder.typicode.com/photos`)
);

</script>

</body>

</html>

limit 设置为 10,offset 设置为 0。每页可以返回的最大数据为 150。

  • jsonplaceholder.typicode.com/photos 返回 5000 张照片。限制和偏移是没有意义的
  • @Doo9104 这只是我放的一个网址,因为我无法分享我的真实网址。我只想知道如何在这样的获取请求中实现偏移和限制。

标签: javascript limit offset


【解决方案1】:

如果您无法更改后端/API 以使用分页 - 您可以使用以下函数将包含 API 结果的数组拆分为更小的块:

function arrChunk(arr, size)
{
  return arr.reduce((acc, e, i) =>
  {
    if (i % size)
    {
      acc[acc.length - 1].push(e);
    }
    else
    {
      acc.push([e]);
    }
    return acc;
  }, []);
}

但最好的选择是更改后端并避免通过网络传输过多的数据。

【讨论】:

    【解决方案2】:
    • 使用Javascript内置数组函数slice()
    • 例如:
       let fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango", "Banana", "Orange", "Lemon", "Apple", "Mango"];
       fruits.slice(0, 3);     // 0 => offset, 3 => limit
    
    • 输出
       output => [Banana,Orange,Lemon] 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-03
      • 2017-06-17
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-26
      • 2023-03-03
      相关资源
      最近更新 更多