首页 > 解决方案 > Print Json data in html tabel by javascript

问题描述

enter image description hereI have JSON data saved in this api https://api.myjson.com/bins/xeza2. I want to print the data in a table by using only JavaScript or jQuery. I have tried a few things. I have used XMLHTTP request. Json.parse() . Every method on stack. This was the first thing I have tried

$(function () {

   var people = [];

   $.getJSON('https://api.myjson.com/bins/xeza2', function (data) {
      $.each(data.info, function (i, f) {
         var tblRow = "<tr>" + "<td>" + f.id + "</td>" +
            "<td>" + f.name + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "</tr>"
         $(tblRow).appendTo("#userdata tbody");
      });

   });

});

标签: javascriptjqueryhtmljsonajax

解决方案


data.info这就是undefined为什么您没有在表格中添加任何内容的原因。您需要将其更改为data.ct_info.

以下代码可以访问请求响应中的 JSON 数据并将其附加到表中。我不确定您希望数据的外观或您尝试访问的属性(因此是undefined's),我将留给您,但以下内容应该可以帮助您入门。

f.job并且f.roll是不存在的属性。

$(function() {

  var people = [];
  $.getJSON('https://api.myjson.com/bins/xeza2', function(data) {
    $.each(data.ct_info, function(i, f) {

      var tblRow = "<tr>" + `<td id=${f.id}>` + "</td>" +
        "<td>" + f.name + "</td>" + "</tr>"
      $(tblRow).appendTo("#userdata tbody");

      var users = []

      //GET USER INFO
      f.Qid_info.forEach((x) => {
        x.user_info.forEach((y) => {
          //avoid duplicates
          var foundUser = users.find((user) => {
            return user.id === y.id
          })
          if (!foundUser) {
            users.push(y)
          }
        })
      })

      $.each(users, function(i, user) {
        var userRow = "<tr>" + `<td id=${user.id}>` + "User's Name:" +
          "</td>" +
          "<td>" + user.name + "</td>" + "</tr>"
        $(userRow).appendTo("#userdata tbody");
      })

    });

  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='userdata'>
  <tbody>

  </tbody>
</table>


推荐阅读