jquery datatables - 从json获取列

mik*_*mik 5 jquery json datatables

在jquery Datatables中是否可以使用服务器端脚本定义列?我需要这样的东西 在此输入图像描述

必须从服务器加载包含日期的列.然后列数可以变化.

Pat*_*hes 5

扩展Kamal Deep Singh所说的话:

您可以动态地动态创建表,然后将数据表应用于它以获取数据表的功能.

// up in the html
<table id="myDatatable" class="... whatever you need..."></table>
Run Code Online (Sandbox Code Playgroud)

然后:

// in the javascript, where you would ordinarily initialize the datatable
var newTable = '<thead><tr>'; // start building a new table contents

// then call the data using .ajax()
$.ajax( {
    url: "http://my.data.source.com",
    data: {}, // data, if any, to send to server
    success: function(data) {
        // below use the first row to grab all the column names and set them in <th>s
        $.each(data[0], function(key, value) {
            newTable += "<th>" + key + "</th>";
        });
        newTable += "</tr></thead><tbody>";                  

        // then load the data into the table
        $.each(data, function(key, row) {
             newTable += "<tr>";
              $.each(row, function(key, fieldValue) {
                   newTable += "<td>" + fieldValue + "</td>";
              });
             newTable += "</tr>";
        });
       newTable += '<tbody>';

       $('#myDatatable').html(newTable); // replace the guts of the datatable's table placeholder with the stuff we just created. 
    }
 });

 // Now that our table has been created, Datatables-ize it
 $('#myDatatable').dataTable(); 
Run Code Online (Sandbox Code Playgroud)

请注意,您可以将设置放在.dataTable()中,但不是'sAjaxSource'或任何相关的数据获取函数 - 这是将数据表应用于现有的表,我们是动态创建的.

好的,所以这是一种hacky方式,但它应该工作.

目前没有内置的方法可以动态地使用数据表.请参见:https://github.com/DataTables/DataTables/issues/273


Dan*_*iel 5

我想我找到了你想要的东西

我会粘贴一些代码+发布链接到类似的Q',你将获得更多信息......

$.ajax( {
    "url": 'whatever.php',
    "success": function ( json ) {
        json.bDestroy = true;
        $('#example').dataTable( json );
     },
    "dataType": "json"
} );
Run Code Online (Sandbox Code Playgroud)

其中json是这样的

{

"aaData": [
[ "2010-07-27 10:43:08", "..."], [ "2010-06-28 17:54:33", "..."],
[ "2010-06-28 16:09:06", "..."], [ "2010-06-09 19:15:00", "..."]
] ,

 "aaSorting": [
  [ 1, "desc" ]
 ],

 "aoColumns": [
   { "sTitle": "Title1" },
   { "sTitle": "Title2" }
 ]

}
Run Code Online (Sandbox Code Playgroud)

这里是原始主题的链接

通过JSON数组(ajax)定义列