javascript - 如何获取 api 数据并在 HTML 表中查看
问题描述
在我的代码中,我想从 api 获取数据并使用 javascript 在 html 表中查看。
fetch("http://dummy.restapiexample.com/api/v1/employees").then(
res => {
res.json().then(
data => {
console.log(data);
if (data.length > 0) {
var temp = "";
data.forEach((itemData) => {
temp += "<tr>";
temp += "<td>" + itemData.id + "</td>";
temp += "<td>" + itemData.employee_name + "</td>";
temp += "<td>" + itemData.employee_salary + "</td>";
});
document.getElementById('data').innerHTML = temp;
}
}
)
}
)
<div class="container">
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Employee Name</th>
<th>Salary</th>
</tr>
</thead>
<tbody id="data">
</tbody>
</table>
</div>
api 数据可以查看,但是当我想将这些数据查看到 html 表时,什么也没有显示。知道我如何将这些获取的数据显示到 html 表中。
解决方案
您一直在使用该data
对象。但是,如果您检查控制台,您的数组就在data.data
. 所以你需要使用data.data
来遍历数组。
fetch("http://dummy.restapiexample.com/api/v1/employees").then(
res => {
res.json().then(
data => {
console.log(data.data);
if (data.data.length > 0) {
var temp = "";
data.data.forEach((itemData) => {
temp += "<tr>";
temp += "<td>" + itemData.id + "</td>";
temp += "<td>" + itemData.employee_name + "</td>";
temp += "<td>" + itemData.employee_salary + "</td></tr>";
});
document.getElementById('data').innerHTML = temp;
}
}
)
}
)
<div class="container">
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Employee Name</th>
<th>Salary</th>
</tr>
</thead>
<tbody id="data">
</tbody>
</table>
</div>
推荐阅读
- javascript - 拒绝在 Electron 中设置不安全的标头错误
- java - 编写布局管理器对象后我的应用程序崩溃
- javascript - Puppeteer - 在 div 内向下滚动(一个站点上有多个滚动条)
- asp.net - 在 Visual Studio 上使用 VB.NET
- ios - 如何从另一个类引用已经创建的视图控制器?
- java - Spring Boot Lazy Loading OrderLine items on Orders GetMapping Request
- azure - 将 VSTS 请求创建为未分配时的通知
- c# - 使用 VSTO 在 Word 文档的每一页上插入一个矩形
- javascript - 我们能否创建一个接受组件并为其添加和应用额外道具的 HoC 或组合?
- python - Python 执行时间