我从 fetch api 调用中返回了大量数据。我想 limit 每页显示的数据为 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 条数据。
回答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;
}, []);
}
但最好的选择是更改后端并避免通过网络传输过多的数据。