【问题标题】:Dynamic column header in datatable from json array来自json数组的数据表中的动态列标题
【发布时间】:2016-06-17 08:47:39
【问题描述】:

我想用动态列标题和列数据填充数据表。我可以成功填充动态列数据,但无法实现动态列。我正在使用从 JSON AJAX 请求中获得的数组。我的代码是这样的:

<body>
    <table id="example" class="display" cellspacing="0" width="100%" border="1"></table>
</body>
var JSONResult = '{"column1":"data1","column2":"data2","column3":"data3","columnN":"dataN"}';
var row_dtable = new Array();
var dtable_api = $('#example').dataTable();

$.each(JSONResult , function(key, value) {
    row_dtable.push(value);
}); 
dtable_api.api().row.add(row_dtable).draw(false);  

提前致谢。

【问题讨论】:

  • 什么是attributes
  • 对不起,我已经编辑了代码..

标签: javascript jquery html json datatables


【解决方案1】:

Datatables 在创建后无法更改其结构。您必须 destroy 它,然后使用一组新列重新创建。

补充阅读:How to dynamically change Datatables multiple column headers using ajax and jquery without refreshing the webpage?

【讨论】:

    【解决方案2】:

    理想情况下,您的JSONResult 将始终具有相同的列,并且只会更新数据。为此,解决方案是在表的标题中创建一次columns,然后使用数据表 API 添加数据。

    首先,您应该像这样更改表格 HTML,这应该不是问题。

    <body>
     <table id="example" class="display" cellspacing="0" width="100%" border="1">
       <thead>
         <tr></tr>
       </thead>
     </table>
    </body>
    

    然后你通过jQuery创建标题

       var JSONResult = [{ "column1": "data1", "column2": "data2", "column3": "data3", "columnN": "dataN" },
                { "column1": "data1", "column2": "data2", "column3": "data3", "columnN": "dataN" }];
    
            $.each(JSONResult[0], function (key, value) {
                $('#example thead tr:first-child').append($('<th>', {
                    text: key
                }));
            });
    

    最后,将数据添加到 dataTable

            var row_dtable = new Array();
            var dtable_api = $('#example').dataTable();
            $.each(JSONResult, function (i, l) {
                $.each(l, function (key, value) {
                    console.log(key + " " + value);
                    row_dtable.push(value);
    
                });
                dtable_api.api().row.add(row_dtable).draw(false);
            });
    

    【讨论】:

      猜你喜欢
      • 2021-09-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-11
      • 2018-04-18
      • 1970-01-01
      • 2020-10-20
      • 2011-03-04
      • 1970-01-01
      相关资源
      最近更新 更多