如何利用randomuser.me API生成6条随机用户数据的HTML表格?
问题描述
需要用HTML制作包含6条随机用户数据的表格,但目前调用randomuser.me API仅能获取并展示1条用户数据,修改ID后无输出,现有代码如下:
<body> <h2>API</h2> <table> <thead> <th>Full Name</th> <th>Age</th> <th>Gender</th> <th>Location</th> <th>Country</th> </thead> <tbody> <tr> <td id="fullname"></td> <td id="age"></td> <td id="gender"></td> <td id="location"></td> <td id="counrty"></td> </tr> <tr> <td id="fullname"></td> <td id="age"></td> <td id="gender"></td> <td id="location"></td> <td id="counrty"></td> </tr> </table> <script> const api_url="https://randomuser.me/api/"; async function getUser() { const response= await fetch(api_url); const data= await response.json(); const user=data.results[0]; let{first, last} = user.name; let{gender, email, phone} = user; let age = user.dob.age; let{city, state, country} = user.location; let fullName = first + " " + last; document.querySelector("#fullname").textContent = fullName; document.querySelector("#age").textContent = age; document.querySelector("#gender").textContent = gender; document.querySelector("#location").textContent = city + " ," + state; document.querySelector("#counrty").textContent= country; } getUser(); </script> </body> </html>
解决方案
核心问题分析
- ID重复违规:HTML要求ID必须唯一,你重复使用
fullname、age等ID,document.querySelector只会匹配第一个元素,这是修改后无输出的直接原因。 - API请求不高效:当前API默认返回1条数据,没必要多次请求,直接通过参数就能批量获取多条数据。
最优实现方案
不需要手动创建多个ID,也不用写重复的静态HTML行,采用动态生成表格内容的方案即可,步骤如下:
- 修改API请求地址,添加
?results=6参数,一次性获取6条用户数据 - 清空tbody的静态行,通过循环遍历返回的用户列表,动态创建表格行和单元格
- 将用户数据填充到对应单元格,再把行追加到tbody中
完整代码示例
<body> <h2>API</h2> <table> <thead> <th>Full Name</th> <th>Age</th> <th>Gender</th> <th>Location</th> <th>Country</th> </thead> <tbody id="userTableBody"> <!-- 动态内容将在这里生成 --> </tbody> </table> <script> // 指定获取6条数据的API地址 const api_url = "https://randomuser.me/api/?results=6"; async function getUsers() { const response = await fetch(api_url); const data = await response.json(); const users = data.results; const tbody = document.getElementById("userTableBody"); // 循环遍历所有用户,生成表格行 users.forEach(user => { const { first, last } = user.name; const { gender } = user; const age = user.dob.age; const { city, state, country } = user.location; const fullName = `${first} ${last}`; const location = `${city}, ${state}`; // 创建表格行并填充内容 const row = document.createElement("tr"); row.innerHTML = ` <td>${fullName}</td> <td>${age}</td> <td>${gender}</td> <td>${location}</td> <td>${country}</td> `; // 将行添加到表格主体 tbody.appendChild(row); }); } getUsers(); </script> </body> </html>
关键说明
- 规避ID问题:动态生成元素完全不需要手动设置ID,既符合HTML规范,又让代码更简洁
- 高效请求:一次API调用获取所有需要的数据,减少网络请求次数,提升加载效率
- 可扩展性强:如果需要调整用户数量,只需要修改API参数中的数字即可,无需改动HTML结构
内容的提问来源于stack exchange,提问作者R4wdha19
相关产品推荐
相关产品推荐

