如何将Ajax响应(对象数组)附加到表的Tbody [英] How To Append Ajax Response (Array Of Objects) To Tbody of A Table

查看:253
本文介绍了如何将Ajax响应(对象数组)附加到表的Tbody的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能帮我解决一下如何将Ajax中的数据追加到现有表格中吗?

Can you please help me to figure it out how to append reciving data from Ajax into a tbody of an existing table?

在我的HTML中,我有一个表格像:

In my HTML I have a Table Like:

<table id="example" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0" width="100%">
    <thead>
    <tr>
    <th valign="middle" class="c-font">Projects </th>
    <th valign="middle" class="c-font">Road Length (Km)</th>
    <th valign="middle" class="c-font">Powerline Length (Km)</th>
    <th valign="middle" class="c-font">Penstock (Km)</th>
    <th valign="middle" class="c-font">Installed Capacity (MW)</th>
    <th valign="middle" class="c-font">Annual Firm Energy (GW/h)</th>
    <th valign="middle" class="c-font">Cost of Energy ($/MWh)</th>
    <th valign="middle" class="c-font">Footprint (Km)</th>
    <th valign="middle" class="c-font">Cost Per Year ($)</th>
    </tr>
    </thead>
    <tbody>    </tbody>
</table>   

和js文件类似

request.done(function(data) {
  console.log(data);
});

控制台中的输出看起来像

which the output in console looks like

这些是要放在> tr>< td>中的值;< / td>< / tr>

AnnualFirmEnergy: "91.2335550"
CostOfEnergy: "183.835765"
CostPerYear: "16771990.38"
Footprint: "182.3077770"
InstalledCapacity: "31.320802"
Penstock: "5000.000000"
PowerLineLength: "37.384781"
ProjectID: "12910"
RoadLength: "29.350976"


推荐答案

尝试使用 $。each()

request.done(function(data) {
  $.each(data, function(key, value) {
      var tr = $("<tr />")
     $.each(value, function(k, v) {
       tr.append(
         $("<td />", {
           html: v
          })[0].outerHTML
       );
      $("table tbody").append(tr)
     })
   })
});

jsfiddle https://jsfiddle.net/11p7e3z6/

jsfiddle https://jsfiddle.net/11p7e3z6/

这篇关于如何将Ajax响应(对象数组)附加到表的Tbody的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆