首页 > 解决方案 > 从rest api获取数据并在html页面中以table的形式打印出来

问题描述

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>


  <script>
var url  = "";
var xhr  = new XMLHttpRequest()
xhr.open('GET', url, true)
xhr.onload = function () {
    var users = JSON.parse(xhr.responseText);
    if (xhr.readyState == 4 && xhr.status == "200") {
    console.log(users);
    console.log(typeof users)
        console.table(users);
    } else {
        console.error(users);
    }
}
xhr.send(null);
    </script>
  </body>
</html>

我想获取restapi数据并在我的HTML页面而不是控制台上以表格的形式打印。从脚本标签出来后,我的对象的范围正在丢失帮助我在html页面上打印数据提前谢谢

标签: javascripthtmlcssajax

解决方案


  <!DOCTYPE html>
    <html lang="en" dir="ltr">
      <head>
        <meta charset="utf-8">
        <title></title>
      </head>
      <body>
       <table>
           <tr id="user"></tr>
       </table>

      <script>
    var url  = "";
    var xhr  = new XMLHttpRequest()
    xhr.open('GET', url, true)
    xhr.onload = function () {
        var users = JSON.parse(xhr.responseText);
        if (xhr.readyState == 4 && xhr.status == "200") {
        console.log(users);
        for(var i = 0; i < user.length;i++){
          var node = document.createElement("td");
          var textnode = document.createTextNode(user[i]);
          node.appendChild(textnode);
          document.getElementById("user").appendChild(node);
        }

    }
    xhr.send(null);
        </script>
      </body>
    </html>

首先,您的响应数据应该以数组形式出现,然后使用 for 循环迭代响应数据,在 HTML 中创建为 tr 提供 id。在 for 循环中创建一个节点作为 TD 并附加您的 TD,最后调用该 ID。


推荐阅读