jQuery表格工具-DataTables

05-26-2017

JQuery外掛 - DataTables

最近幫公司新建查詢含更新欄位頁面,自己手刻還不如使用DataTables這套外掛來的美觀好用,而且這套外掛只需要簡單的設定,就可以使用,加上這套是免費讓大家使用,不需另外付費。

DataTables官方網站

DataTables UI

DataTables - 初始化

DataTables有許多使用的模式,我的所產生的結果並沒有多到會讓服務器產生影響,所以使用服務器端的模式,透過JSON返回排序(order)、分頁(paging)、過濾(filter)。

HTML - 使用前需要引入DataTables的JS跟CSS相關包,這邊用cdn的方式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<html>
<head>
<title>Datatables</title>
<link href="//cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet" />
<link rel="stylesheet" href="main.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" type="text/javascript"></script>
<script src="//cdn.datatables.net/1.10.4/js/jquery.dataTables.min." type="text/javascript"></script>
<style>
body {font-family: calibri;color:#4e7480;}
</style>
</head>
<body>
<div class="container">
<table id="example" class="display nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Address</th>
<th>Phone</th>
<th>DOB</th>
</tr>
</thead>
</table>
</div>
</body>
</html>

DataTable - 使用服務器模式需要將serverSide選項,設置為true,並結合ajax,讓DataTables知道從何處獲取數據。

1
2
3
4
5
6
7
8
9
10
11
12
13
<script>
$(document).ready(function() {
$('#example').DataTable({
//開啟服務器模式
serverSide: true,
//數據來源(包括處理分頁、排序、過濾),即url、action、接口等
ajax: {
url: '/data-source',
type: 'POST'
}
});
});
</script>

Server Side - PHP程式修改DataTable官方網站的Demo,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?php
$table = 'tbl_contact';

$primaryKey = 'id';

$columns = array(
array( 'db' => 'first_name', 'dt' => 0 ),
array( 'db' => 'last_name', 'dt' => 1 ),
array( 'db' => 'address', 'dt' => 2 ),
array( 'db' => 'phone', 'dt' => 3,),
array( 'db' => 'date_of_birth','dt' => 4,
'formatter' => function( $d, $row ) {
return date( 'd-m-Y', strtotime($d));
}
)
);

$sql_details = array(
'user' => 'root',
'pass' => '',
'db' => 'dataTable',
'host' => 'localhost'
);

require( 'datatables/ssp.class.php' );

echo json_encode(
SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);
?>

參考文章:

jQuery DataTable 後端分頁
前端常用功能记录(二)—datatables表格
Export jQuery Datatable Data To PDF, Excel, CSV & Copy with PHP
Export HTML Table to Excel, CSV, JSON, PDF, PNG using jQuery