表格本身可以完全空白,所有欄位與內容都交由 DataTables 產生:
<table class="table table-striped table-bordered table-hover" id="expandabledatatable"></table>
Bootstrap 提供的三個樣式類別分別負責:斑馬紋(-striped)、框線(-bordered)、滑鼠移入高亮(table-hover)。
var oTable = $('#expandabledatatable').dataTable({
"sDom": "Tflt<'row DTTTFooter'<'col-sm-6'i><'col-sm-6'p>>",
"aoColumnDefs": [
{ // 第一欄:展開/收合用的圖示
"bSortable": false,
"aTargets": [0],
"render": function (data, type, full) {
return '<i class="fa fa-plus-square-o row-details"></i>';
}
},
{ "aTargets": [1], "data": "TaskName", "title": "任務名稱" },
{ "aTargets": [2], "data": "CronExpression", "title": "表達式" },
{ "aTargets": [3], "data": "Remark", "title": "說明" },
{ // 狀態欄:依資料決定按鈕樣式
"bSortable": false,
"aTargets": [4],
"title": "運行狀態",
"render": function (data, type, full) {
return full["Enabled"] == true
? '<button class="btn btn-success btn-sm">運行</button>'
: '<button class="btn btn-warning btn-sm">停止</button>';
}
},
{ // 操作欄
"bSortable": false,
"aTargets": [5],
"render": function () {
return '<a href="#" class="btn btn-info btn-xs edit"><i class="fa fa-edit"></i> 編輯</a> '
+ '<a href="#" class="btn btn-danger btn-xs delete"><i class="fa fa-trash-o"></i> 刪除</a>';
}
}
],
"bServerSide": true,
"sAjaxSource": "/Task/GetAllTask",
"aaSorting": [[1, 'asc']],
"aLengthMenu": [[5, 15, 20, -1], [5, 15, 20, "All"]],
"iDisplayLength": 5,
"searching": false,
"bLengthChange": false,
"language": {
"sProcessing": "正在加載數據...",
"sEmptyTable": "沒有資料",
"sInfo": "從 _START_ 到 _END_ / 共 _TOTAL_ 筆",
"oPaginate": { "sPrevious": "上一頁", "sNext": "下一頁" }
},
"fnServerData": function (sSource, aoData, fnCallback) {
$.ajax({
"type": 'POST',
"url": sSource,
"dataType": "json",
"data": { aoData: JSON.stringify(aoData) },
"success": function (resp) { fnCallback(resp); }
});
}
});
資料由後端提供時,這三項缺一不可:
"bServerSide": true, // 開啟伺服器端處理
"sAjaxSource": "/Task/GetAllTask", // 資料來源網址
"fnServerData": function (sSource, aoData, fnCallback) { ... }
fnServerData 是自建請求的入口。DataTables 預設用 GET,而分頁、排序、搜尋的參數被序列化後可能過長,因此範例改成 POST 並把 aoData 轉成 JSON 字串傳送。
伺服器端模式下,DataTables 期望回傳一個包含以下欄位的 JSON:
{
"iTotalRecords": 100, // 過濾前的總筆數
"iTotalDisplayRecords": 20, // 過濾後的總筆數
"aaData": [ // 目前這一頁的資料
{ "TaskName": "任務一", "CronExpression": "0 0/1 * * * ?", "Remark": "說明", "Enabled": true }
]
}
並依請求中的 iDisplayStart、iDisplayLength、sSortCol_0 等參數決定要回傳哪一段資料。這也是伺服器端模式的核心精神:分頁與排序都在後端做,前端只負責顯示,資料量大時才不會卡住瀏覽器。
render 函式產生的按鈕是動態元素,若要綁定事件,務必用事件委派($('#table tbody').on('click', '.edit', ...))。sDom、aoColumnDefs 寫法在 DataTables 1.10+ 已改名為 dom、columnDefs,舊名仍相容但不建議再用於新專案。