如何在HTML中展示100条JSON接口数据?新手技术求助
如何展示全部100条帖子数据?
你现在的问题有两个核心点:一是请求的API地址只获取了单条帖子(posts/1),二是HTML里只有一组固定的带id的元素,没法复用显示多条内容。要展示全部100条帖子,必须用循环遍历返回的帖子数组,同时动态生成对应的HTML元素。
步骤1:修改API请求地址
把原来的https://jsonplaceholder.typicode.com/posts/1改成https://jsonplaceholder.typicode.com/posts,这样就能获取到包含100条帖子的数组。
步骤2:调整HTML结构
删掉原来固定的<a>、<h3>、<p>元素,换成一个空的容器,用来承载所有动态生成的帖子内容:
<!DOCTYPE html> <html> <head> <script src="fetch.js"></script> <title>List</title> <style> /* 可选:加一点点样式让列表更美观 */ .post-item { margin: 1rem 0; padding: 1rem; border-bottom: 1px solid #eee; } .post-title { margin-top: 0; color: #2d3748; } .post-body { color: #4a5568; line-height: 1.5; } </style> </head> <body> <div id="posts-container"></div> </body> </html>
步骤3:修改JavaScript代码,循环生成帖子内容
遍历API返回的帖子数组,为每个帖子创建对应的HTML元素,然后添加到容器里:
const api_url = 'https://jsonplaceholder.typicode.com/posts'; async function getPosts() { const response = await fetch(api_url); const posts = await response.json(); // 这里返回的是数组,不是单个对象 const container = document.getElementById('posts-container'); // 循环遍历每个帖子 posts.forEach(post => { // 创建帖子容器 const postItem = document.createElement('div'); postItem.className = 'post-item'; // 创建标题元素 const titleElement = document.createElement('h3'); titleElement.className = 'post-title'; titleElement.textContent = post.title; // 创建正文元素 const bodyElement = document.createElement('p'); bodyElement.className = 'post-body'; bodyElement.textContent = post.body; // 把标题和正文添加到帖子容器里 postItem.appendChild(titleElement); postItem.appendChild(bodyElement); // 把帖子容器添加到页面的大容器里 container.appendChild(postItem); }); } getPosts();
关键说明
- 因为API返回的是数组,所以必须用
forEach(或者普通for循环)遍历每一项帖子数据 - 不能用固定的
id来绑定内容,因为id在页面中是唯一的,多次使用会导致只有最后一条数据生效,所以要动态创建元素并添加类名来控制样式 - 如果需要给每个帖子加跳转链接(比如到详情页),可以把
postItem改成<a>标签,设置href属性(比如href="detail.html?id=${post.id}")
内容的提问来源于stack exchange,提问作者darkman106
相关产品推荐
相关产品推荐

