如何从API获取特定范围数据?博客站点分页加载文章实现
实现「查看更多」加载第11-20篇文章的方案
核心思路
JSONPlaceholder的API支持_limit(限制返回数量)和_skip(跳过指定数量条目)两个参数组合实现分页。我们只需要维护一个偏移量变量,每次点击按钮时更新偏移量,请求对应区间的文章,再把新文章追加到页面即可。
修正并优化代码
首先修正你原代码里的小问题:data.json()是异步操作,需要加await,否则会返回Promise而非实际数据。然后改造代码支持分页加载:
<!-- 页面结构示例 --> <div id="posts-container"></div> <button id="load-more-btn">查看更多</button>
// 维护分页状态:已跳过的文章数量,初始为10(前10篇已加载) let currentSkip = 10; const API_URL = "https://jsonplaceholder.typicode.com/posts"; const POSTS_PER_PAGE = 10; // 封装通用的文章获取函数,支持传入偏移量 async function getPosts(skip = 0, limit = POSTS_PER_PAGE) { try { const response = await fetch(`${API_URL}/?_limit=${limit}&_skip=${skip}`); if (!response.ok) throw new Error("请求失败"); return await response.json(); } catch (err) { console.error(err); return []; } } // 渲染文章到页面的函数 function renderPosts(posts) { const container = document.getElementById("posts-container"); posts.forEach(post => { const postElement = document.createElement("div"); postElement.innerHTML = ` <h3>${post.title}</h3> <p>${post.body}</p> <hr> `; container.appendChild(postElement); }); } // 初始化加载前10篇 getPosts().then(renderPosts); // 绑定查看更多按钮点击事件 document.getElementById("load-more-btn").addEventListener("click", async () => { const newPosts = await getPosts(currentSkip); if (newPosts.length === 0) { // 无更多文章时禁用按钮 const btn = document.getElementById("load-more-btn"); btn.disabled = true; btn.textContent = "已加载全部文章"; return; } renderPosts(newPosts); // 更新偏移量,准备下一次加载 currentSkip += POSTS_PER_PAGE; });
关键说明
_skip=${currentSkip}:每次请求时跳过已加载的文章,第一次点击时_skip=10,对应返回第11-20篇文章。- 追加渲染:
renderPosts用appendChild实现文章累加,而非覆盖原有内容。 - 边界处理:当返回的文章数组为空时,说明已加载完所有100篇,此时禁用按钮并提示状态。
内容的提问来源于stack exchange,提问作者Eshada
相关产品推荐
相关产品推荐

