如何使用async await将JSON数据渲染到HTML指定id的div容器中
实现方案
首先确保你的HTML文件中存在目标渲染容器:
<div id="content"></div>
你已有的代码已经完成了JSON数据的异步加载逻辑,只需要在拿到users数组后补充DOM渲染的代码即可,修改后的完整代码如下:
// My async await async function loadUsers() { const response = await fetch("./user.json"); // 可选补充:响应状态判断,避免接口返回4xx/5xx时错误信息不明确 if (!response.ok) { throw new Error(`加载失败,状态码:${response.status}`); } return response.json(); } document.addEventListener('DOMContentLoaded', async () => { let users = []; // 提前声明变量,避免隐式成为全局变量 try { users = await loadUsers(); // 以下为需要补充的渲染逻辑 const contentDiv = document.getElementById('content'); // 清空容器原有内容,避免重复渲染 contentDiv.innerHTML = ''; // 遍历所有用户数据生成对应标签 users.forEach(user => { // 生成ID行 const idP = document.createElement('p'); idP.textContent = `ID: ${user.id}`; contentDiv.appendChild(idP); // 生成用户名校 const usernameP = document.createElement('p'); usernameP.textContent = `Username : ${user.username}`; contentDiv.appendChild(usernameP); // 生成年龄行 const ageP = document.createElement('p'); ageP.textContent = `Age : ${user.age}`; contentDiv.appendChild(ageP); // 可选:不同用户之间加水平分隔线,不需要可以删除本行 contentDiv.appendChild(document.createElement('hr')); }); } catch (e) { console.log("ERROR"); console.log(e); // 可选补充:加载失败时给页面提示 const contentDiv = document.getElementById('content'); contentDiv.innerHTML = '<p>用户数据加载失败,请稍后重试</p>'; } console.log(users); })
内容的提问来源于stack exchange,提问作者user14186487
相关产品推荐
相关产品推荐

