jQuery Datatable填充第二个标题行

时间:2014-08-15 11:15:07

标签: jquery datatables

我有一个jQuery Datatable,标题中有2行。我想在这个标题的第二行填充一些我从服务器返回的值,以JSON格式,以及表格内容的所有数据。

我看了看并试图找到一种方法来做到这一点,但我正在努力。

有人可以告诉我,一旦从服务器获取数据,请将这些值输入标题的最佳方法是什么?

以下是我如何从服务器返回JSON并填充表格的行:

$.ajax({
    url: "<?php echo $this->url($reportResource)?>"
}).done(function(data) {
    // populate the data in to the rows of the table
    reportTable.rows.add(data.rows).draw();

    // the data param here contains an item in the array which contains all 
    // of the totals I'd like to put in the 2nd header row:
    var totalValues = data.totals;
});

以下是表格的HTML:

<table class="table table-striped" id="report-table">
    <br/>
    <thead>
        <th>Impressions</th>
        <th>Sold</th>
        <th>Unsold</th>
        <th>Percentage</th>
        <th>eCPM</th>
        <th>Revenue</th>
        <th>Commision</th>
        <th>Net</th>
    </tr>
    <tr>
        <th style="text-align:right">Totals:</th>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
        <th></th>
    </tr>
    </thead>
    <tbody>
    </tbody>
</table>

返回的JSON是:

{
 "rows": {
     "0":{"site":"<website1>","imps":20276,"sold":17308,"unsold":2968,"percentage":85.3620043401,"eCpm":0.0909454034326,"grossRevenue":1.844009,"commission":0.5532027,"netRevenue":1.2908063},
     "1":{"site":"<website2>","imps":4485,"sold":3900,"unsold":585,"percentage":86.9565217391,"eCpm":0.0833068004459,"grossRevenue":0.373631,"commission":0.1120893,"netRevenue":0.2615417},
     "2":{"site":"<website3>","imps":37,"sold":34,"unsold":3,"percentage":91.8918918919,"eCpm":0.0665405405405,"grossRevenue":0.002462,"commission":0.0007386,"netRevenue":0.0017234},
 }
 "totals":{"imps":24798,"sold":21242,"unsold":3556,"percentage":85.6601338818,"eCpm":0.0895274618921,"grossRevenue":2.220102,"commission":0.6660306,"netRevenue":1.5540714}
}

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

首先,您的JSON响应无效。您可能希望看一下 - 2:{}末尾有一个逗号 - 删除该逗号,并且您在"totals"之前也缺少逗号。

在您的成功函数中,您可以在<td>附加值,我试图在此处说明:

var row = $('#totals');

// add tds to row
for (value in data.totals) {
    row.append('<td>'+ data.totals[value] +'</td>');
}

小提琴:http://jsfiddle.net/z7p3qnnt/