2011-12-29 82 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)