如何在html表

时间:2017-10-23 05:01:37

标签: javascript jquery html json ajax

这里我使用AJAX调用从API获取JSON数据。我需要以html格式显示数据。谁能告诉我该怎么做?我的JSON数据如下所示:

"vjginteractive":{"signup_date_time":"2017-04-11 01:34:19","package_id":"2","total_leads":0},"vmlsingapore":{"signup_date_time":"2016-05-31 07:33:38","package_id":"2","total_leads":"not_available"},"vodkafashionindia":{"signup_date_time":"2016-03-17 18:15:48","package_id":"2","total_leads":0}

这是我尝试过的。如何以表格格式显示公司名称,访问和潜在客户?

$(document).ready(function()
  {
var X = [];
var Y = [];
var data = [];
function loadJSON(callback) {
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', 'https://api.myjson.com/bins/nihnp', true);
    xobj.onreadystatechange = function() {
        if (xobj.readyState == 4 && xobj.status == "200") {
            callback(xobj.responseText);
        }
    }
    xobj.send(null);
}
loadJSON(function(response) {
    var response;
    var field=JSON.parse(response);
    var values=[];
    for (var i = 0; i < field.length; i++) {
        var $this=field[i];
        for (var key in $this) {
          if ($this.hasOwnProperty(key)) {
            var val = $this[key];
            values.push({"x":val.total_visits,"y":val.total_leads});
          }
        }
    }
});
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="chartContainer" style="height: 560px; width: 100%;"></div>
</head>

1 个答案:

答案 0 :(得分:3)

您可以使用Object获取Object.keys个密钥,该密钥将为您返回包含所有密钥的Array。然后你可以使用forEach来迭代它们。

&#13;
&#13;
$(document).ready(function() {
  function loadJSON(callback) {
    const data = '{"vjginteractive":{"signup_date_time":"2017-04-11 01:34:19","package_id":"2","total_leads":0},"vmlsingapore":{"signup_date_time":"2016-05-31 07:33:38","package_id":"2","total_leads":"not_available"},"vodkafashionindia":{"signup_date_time":"2016-03-17 18:15:48","package_id":"2","total_leads":0}}';
    callback(JSON.parse(data));
  }

  loadJSON(function(response) {
    const $table = $('#chartContainer');
    Object.keys(response)
      .forEach((key) => {
        const field = response[key];
        $table.append(
          `<tr>
          <td>${field.signup_date_time}</td>
          <td>${field.package_id}</td>
          <td>${field.total_leads}</td>
          </tr>`);
      });
  });
});
&#13;
td {
  border: 1px solid rgba(0, 0, 0, .2);
  padding: 5px 10px;
}
&#13;
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <table id="chartContainer"></table>
</head>
&#13;
&#13;
&#13;