2011-12-29 63 views
5

在jquery Datatables是否可以使用服务器端脚本定义列? 我需要的是这样的 enter image description herejquery datatables - 从json获取列

列的日期必须从服务器加载。 然后列数可能会有所不同。

+1

你为什么不使用JSON获得完整的数据,然后创建一个HTML表格,你可以把它展示给用户 – Moons 2011-12-29 08:07:51

+0

我不太明白你的“创建HTML表”的意思。用Javascript创建? – mik 2011-12-29 08:10:22

+0

当你得到JSON,然后你可以使用JSON.parse解析它,然后你可以迭代对象来使用JQuery创建一个HTML表格 – Moons 2011-12-29 08:19:22

回答

5

要展开什么卡迈勒深辛格说:

您可以动态即时创建表,然后应用数据表把它拿到数据表功能。

// up in the html 
<table id="myDatatable" class="... whatever you need..."></table> 

然后:

// 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(); 

注意,你可以把设置在.dataTable()为正常,但是,并不是“sAjaxSource”或任何相关的数据,得到的功能 - 这是将数据表应用到已经存在的表格中,这是我们即时创建的表格。

好的,所以这是一种很好的做法,但它应该起作用。

目前还没有一种内置的方法可以动态地对数据表进行操作。在这里看到:https://github.com/DataTables/DataTables/issues/273

+0

谢谢,但我正在寻找一个更方便的方式,类似于这个“sAjaxSource”:“scripts/server_processing.php” – mik 2011-12-29 10:55:34

5

我想我已经找到你要找的

我会贴一些代码+发布一个链接到一个类似Q”中,你会得到更多的信息.​​..

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

其中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" } 
] 

} 

这里原始线程链接

Column definition via JSON array (ajax)