【问题标题】:Display data returned with Ajax in table format以表格形式显示 Ajax 返回的数据
【发布时间】:2019-01-03 20:05:03
【问题描述】:

我正在使用 Ajax+Jquery 从 PHP api 获取数据。在我最后一步的那个 PHP api 中-

$data_enc = json_encode($data); 回声 $data_enc;

我得到了这个返回-

{"headers":["Age","Count","Consent","Intent"],"data":{"17":{"Age":"17","Count":2,"Consent":"2","Intent":0},"18":{"Age":"108","Count":3,"Consent":"3","Intent":0},"115":{"Age":"115","Count":1,"Consent":"1","Intent":0},"117":{"Age":"117","Count":2,"Consent":"2","Intent":0},"118":{"Age":"118","Count":1,"Consent":"1","Intent":0},"Totals":{"Age":"Total","Count":67,"Consent":67,"Intent":0}}}

在 Jquery 方面,

success: function(data){
    alert(typeof(data)); //returns string
},

当我在 jQuery Ajax 成功中执行 typeof(data) 时,它说它是一个字符串。 我需要在表格中显示这些数据,其中列有 Age、Count、Consent、Intent。

我尝试在 jQuery 端循环对象,但无法获得所需的结果。

【问题讨论】:

  • 你在 ajax 调用中使用dataType: "json", 吗?
  • 使用JSON.parse()解析JSON! JSON 没有数据类型。
  • “它说它是一个字符串”,“我尝试循环遍历对象”。字符串!=对象。你的第一个谷歌应该是“如何将 json 转换为对象?”
  • @VincentDecaux 我使用了它,但它出错了,这让我再次想到 Taplar 所说的,我得到的是一个字符串而不是一个对象。但是不会做一个 json_encode 使它成为一个 JSON 对象吗?
  • @manishk 你想使用 JSON.parse(jsonData) 函数 -> developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

标签: javascript php jquery ajax


【解决方案1】:

在您的 ajax 请求中使用 dataType: 'json'。

要建表:

HTML:

<table id="myTable">
   <thead></thead>
   <tbody></tbody>
</table>

JS:

$.ajax({
   url: '...',
   dataType: 'json',
   success: function (result) {
       $('#myTable tr').empty();
       var header = $('#myTable thead');
       var body = $('#myTable tbody');
       var hTr;
       $('#myTable thead').append(hTr = $('<tr>'));
       // Headers
       for (var h = 0; h < result.headers.length; h++) {
          hTr.append($('<th>', { text: result.headers[h] }))
       }
       // Body
       for (var d in result.data) {
          var data = result.data[d];
          $('#myTable tbody').append($('<tr>')
              .append($('<td>', { text: data.Age }))
              .append($('<td>', { text: data.Count }))
              .append($('<td>', { text: data.Consent }))
              .append($('<td>', { text: data.Intent }))
          )
       }
   }
})

【讨论】:

  • 您缺少大括号- .append($('', { text: data.Age })) 感谢您的回答。
  • 另一个问题 - 当我多次发送请求时,数据会附加到表中( 和 )。如何获取仅包含最新请求结果的表格?
  • 没关系,只是用 $("#myTable tr").remove();在顶部,就在成功之内。
猜你喜欢
相关资源
最近更新 更多
热门标签