如何将Ajax响应(对象数组)附加到表的Tbody
能帮我解决一下如何将Ajax中的数据追加到现有表格中吗?
在我的HTML中,我有一个表格:
Projects Road Length (Km) Powerline Length (Km) Penstock (Km) Installed Capacity (MW) Annual Firm Energy (GW/h) Cost of Energy ($/MWh) Footprint (Km) Cost Per Year ($)
和js文件是一样的
request.done(function(data) { console.log(data); });
控制台中的输出看起来像
这些是要放在>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 = $(" ") $.each(value, function(k, v) { tr.append( $(" ", { html: v })[0].outerHTML ); $("table tbody").append(tr) }) }) });
jsfiddle https://jsfiddle.net/11p7e3z6/
让我展示访问json数组元素的两个基本原则。 这些原则如下面的代码所示 – 请阅读我的评论。 我想这对我们的社区有用。
var data = {1:{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"},2:{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"},3:{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"}} for(var i in data) //i = 1, 2, 3 ... { var rn = $(' '); //first approach to add data (not flexible) rn.append(''+data[i].ProjectID+' '); rn.append(''+data[i].RoadLength+' '); rn.append(''+data[i].PowerLineLength+' '); // here add all columns $('#example').append(rn); //second - right - approach to add data. //in this casу data in your JSON array //have had order like your table head arrangement var rd = $(' '); var o=data[i]; for(var j in o)//j='AnnualFirmEnergy', ... { rd.append(''+o[j]+' '); $('#example').append(rd); } }
TABLE { width: 300px; border: 1px solid black; border-bottom: none; } TD, TH { padding: 3px; } TH { text-align: left; background: black; color: white; border: 1px solid white; } TD { border-bottom: 1px solid black; }
Projects Road Length (Km) Powerline Length (Km) Penstock (Km) Installed Capacity (MW) Annual Firm Energy (GW/h) Cost of Energy ($/MWh) Footprint (Km) Cost Per Year ($)
如果你不使用某种模板引擎将数据克隆到DOM中,你很快就会陷入一个混乱的不可维护的代码迷宫中。
下面是一个使用dna.js引擎的例子,这是我所贡献的库,但这种方法很常见。 基本思想是在HTML中定义数据字段,然后将JSON数据传递给引擎进行克隆。
HTML
Projects Road Length (Km) Powerline Length (Km) Penstock (Km) ~~AnnualFirmEnergy~~ ~~CostOfEnergy~~ ~~CostPerYear~~ ~~Footprint~~
...
JavaScript的
function handle(data) { dna.clone('energy', data); } request.done(handle);
是的,就这么简单。 请注意,JS中没有HTML,因此JS更易于维护,HTML更容易设置样式。