我有一个要求,每次单击按钮时,我必须发出 API 请求从客户端获取/加载新项目。 初始页面加载会加载一些项目,并且从客户端 api 调用获取的新项目应抵消这些项目。但是该 API 不支持偏移量。如何使用 page 和 perPage 来实现此目的。
例如:假设页面上有 8 个现有项目。单击按钮时的新项目应每次加载 10 个项目(项目 9-18、19-28、29-38 等)。 我如何使用 page 和 perPage 来完成这项工作,而不需要为每个按钮单击进行多次调用?
我让它与每个按钮点击的多个 api 请求一起工作,但我试图看看是否有一种有效的方法来为每个按钮点击使用单个 api 调用。
不确定您的响应数据结构或 API URL 是什么样的,但类似的东西应该可以工作。
function fetchItems() {
//API request, parameters are current page and perPage
fetch(`your-api-url?page=${currentPage}&perPage=${perPage}`)
.then(response => response.json())
.then(data => {
// Display items on the page
renderItems(data.items);
})
.catch(error => {
console.error('Error fetching items:', error);
});
}
function renderItems(items) {
// Display items
}
// Initial page load
fetchItems();
// Event listener, button click that loads more items
document.getElementById('loadMoreButton').addEventListener('click', function() {
//Increment page number
currentPage++;
// Fetch items for the next page
fetchItems();
});
每次单击“加载更多”按钮时,currentPage 变量都会递增,并使用更新的页面参数发出新的 API 请求以获取下一组项目。因此,每次单击按钮都会调用一个 API。