首页 > 解决方案 > 如何获取 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 表中。

标签: javascripthtmlapi

解决方案


您一直在使用该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>


推荐阅读