DataTables使用入門


簡介

Datatables是一款jquery表格插件。它是一個高度靈活的工具,可以將任何HTML表格添加高級的交互功能。

  • 分頁,即時搜索和排序
  • 幾乎支持任何數據源:DOM, javascript, Ajax 和 服務器處理
  • 支持不同主題 DataTables, jQuery UI, Bootstrap, Foundation
  • 各式各樣的擴展: Editor, TableTools, FixedColumns ……
  • 豐富多樣的option和強大的API
  • 支持國際化
  • 超過2900+個單元測試
  • 免費開源 ( MIT license )! 商業支持
  • 更多特性請到DataTables中文網查看

下載

可以到DataTables中文網下載最新版本的文檔。

下載完目錄如下:
DataTables目錄

我們將使用media目錄下的文件。
media目錄

簡單使用

在項目中使用Datatables,只需要引用三個文件即可,jQuery庫,一個DT的核心js文件和一個DT的css文件。

demo目錄

demo目錄

demo.html

<!DOCTYPE HTML>
<html>
	<head>
		<title>DataTables Demo</title>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<link rel="stylesheet" href="css/jquery.dataTables.css"></link>
	</head>
	<body>
		<table id="table_id_example" class="display">
			<caption>最近交易記錄</caption>
		</table>
	</body>
	
	<script src="js/jquery.js"></script>
	<script src="js/jquery.dataTables.js"></script>
	<script src="js/demo.js"></script>
</html>

demo.js

$(document).ready( function () {
	var data = [
        [
            "20170527150032890",
            "-0.10  CNY",
            "提現",
            "失敗",
            "2017-05-27 15:00:32",
            "提現",
			""
        ],
        [
            "20170527145824609",
            "-3.00  CNY",
            "凍結",
            "成功",
            "2017-05-27 14:58:24",
            "凍結金額",
			""
        ],
		[
            "20170527145704263",
            "-3.00  CNY",
            "提現",
            "失敗",
            "2017-05-27 14:57:04",
            "提現",
			""
        ],
		[
			"20170527145226988",
			"-100.00  CNY",
			"凍結",
            "成功",
			"2017-05-27 14:52:26",
			"凍結金額",
			""
		],
		[
			"20170525121845479",
			"-0.01 CNY",
			"提現",
            "已受理",
			"2017-05-27 09:28:09",
			"重新提現",
			"<button class='btn btn-warning btn-block' onclick=alert('haha') >取消提現</button>"
		],
		[
			"20170527144117493",
			"-0.11 CNY",
			"提現",
            "成功",
			"2017-05-27 00:00:00",
			"虛擬提現(凍結金額)",
			""
		],
		[
			"20170526165926389",
			"-12.00 CNY",
			"提現",
            "已受理",
			"2017-05-26 16:59:26",
			"提現",
			"<button class='btn btn-warning btn-block' onclick=alert('haha') >取消提現</button>"
		],
		[
			"20170526165802358",
			"-2.00 CNY",
			"提現",
            "已受理",
			"2017-05-26 16:58:02",
			"提現",
			""
		],
		[
			"20170526165520190",
			"-1.00 CNY",
			"提現",
            "已受理",
			"2017-05-26 16:55:20",
			"提現",
			"<button class='btn btn-warning btn-block' onclick=alert('haha') >取消提現</button>"
		],
		[
			"20170526161241519",
			"-1.00 CNY",
			"提現",
            "已受理",
			"2017-05-26 16:12:41",
			"提現",
			""
		],
		[
			"20170526165802358",
			"-99.00 CNY",
			"提現",
            "已受理",
			"2017-05-26 16:58:02",
			"提現",
			""
		],
		[
			"20170526165520190",
			"-99.00 CNY",
			"提現",
            "已受理",
			"2017-05-26 16:55:20",
			"提現",
			""
		],
		[
			"20170526161241519",
			"-99.00 CNY",
			"提現",
            "已受理",
			"2017-05-26 16:12:41",
			"提現",
			""
		]
    ];

    //DataTables 初始化
    $('#table_id_example').DataTable( {
		data: data,
		columns: [
            { title: '批次號' },
            { title: '金額' },
            { title: '交易類型' },
            { title: '交易狀態' },
			{ title: '交易時間' },
			{ title: '交易信息' },
			{ title: '操作' }
        ]
    } );
} );

結果

簡單使用結果

添加國際化

Datatables中所使用的語言選項是通過 language 來配置的。 這是一個對象字符串,通過一個參數來描述Datatables的每個部分。

Datatables默認的是英語,這里我們改成中文。在demo.js文件添加 language 配置項,使其DataTables初始化代碼像這樣:

//DataTables 初始化
$('#table_id_example').DataTable( {
    data: data,
    columns: [
        { title: '批次號' },
        { title: '金額' },
        { title: '交易類型' },
        { title: '交易狀態' },
        { title: '交易時間' },
        { title: '交易信息' },
        { title: '操作' }
    ],
    // 國際化
    language: {
        "sProcessing": "處理中...",
        "sLengthMenu": "顯示 _MENU_ 項結果",
        "sZeroRecords": "沒有匹配結果",
        "sInfo": "顯示第 _START_ 至 _END_ 項結果,共 _TOTAL_ 項",
        "sInfoEmpty": "顯示第 0 至 0 項結果,共 0 項",
        "sInfoFiltered": "(由 _MAX_ 項結果過濾)",
        "sInfoPostFix": "",
        "sSearch": "搜索:",
        "sUrl": "",
        "sEmptyTable": "表中數據為空",
        "sLoadingRecords": "載入中...",
        "sInfoThousands": ",",
        "oPaginate": {
            "sFirst": "首頁",
            "sPrevious": "上頁",
            "sNext": "下頁",
            "sLast": "末頁"
        },
        "oAria": {
            "sSortAscending": ": 以升序排列此列",
            "sSortDescending": ": 以降序排列此列"
        }
    }
} );

結果如圖
國際化

關於表列

上面我們的寫法是動態添加title

columns: [
    { title: '批次號' },
    { title: '金額' },
    { title: '交易類型' },
    { title: '交易狀態' },
    { title: '交易時間' },
    { title: '交易信息' },
    { title: '操作' }
]

官網是另一種寫法,首先在table里寫好表列字段名,如:

<thead>
    <tr>
        <th>name</th>
        <th>position</th>
        <th>salary</th>
        <th>office</th>
    </tr>
</thead>

然后上面columns寫法稍微有點不同

columns: [
    { data: 'name' },
    { data: 'position' },
    { data: 'salary' },
    { data: 'office' }
]

這樣也是完全OK的,具體怎么用看自己喜好和實際業務了。

服務器支持

一次性處理大量數據DataTables性能會下降,因為 DT 需要渲染,數據越多,速度就越慢。

為了解決這個問題, DataTables 提供了服務器模式,把本來客戶端所做的事情交給服務器去處理, 比如排序(order)、分頁(paging)、過濾(filter)。

啟用服務器模式時,每次請求 DataTables 會向服務器發送一些參數(當前分頁,排序,搜索參數等),服務器則返回組裝好的數據。

demo.html

<!DOCTYPE HTML>
<html>
	<head>
		<title>DataTables Demo</title>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<link rel="stylesheet" href="css/jquery.dataTables.css"></link>
	</head>
	<body>
		<table id="city" class="display">
			<caption>city</caption>
			<thead>
				<tr>
					<th>id</th>
					<th>name</th>
					<th>countryCode</th>
					<th>district</th>
					<th>population</th>
				</tr>
			</thead>
		</table>
	</body>
	
	<script src="js/jquery.js"></script>
	<script src="js/jquery.dataTables.js"></script>
	<script src="js/demo.js"></script>
</html>

demo.js

$(document).ready( function () {
    //DataTables 初始化
    $('#country').DataTable( {
		"processing": true,		//開啟加載等待提示,提示信息是下面language中的sProcessing配置
        "serverSide": true,		//打開服務器模式
		"ajax": {
			"url": "city/getall",
			"type": "POST",
			"data": function(d){	//d包含了DataTables發送到服務器的參數,這里還可以根據自己的業務添加參數
                //可以自定義一些業務參數
                //d.xxx = "xxx";
			}
		},
		"columns": [
            { "data": 'id' },
            { "data": 'name' },
            { "data": 'countryCode' },
            { "data": 'district' },
			{ "data": 'population' }
        ],
		// 國際化
		language: {
			"sProcessing": "處理中...",
			"sLengthMenu": "顯示 _MENU_ 項結果",
			"sZeroRecords": "沒有匹配結果",
			"sInfo": "顯示第 _START_ 至 _END_ 項結果,共 _TOTAL_ 項",
			"sInfoEmpty": "顯示第 0 至 0 項結果,共 0 項",
			"sInfoFiltered": "(由 _MAX_ 項結果過濾)",
			"sInfoPostFix": "",
			"sSearch": "搜索:",
			"sUrl": "",
			"sEmptyTable": "表中數據為空",
			"sLoadingRecords": "載入中...",
			"sInfoThousands": ",",
			"oPaginate": {
				"sFirst": "首頁",
				"sPrevious": "上頁",
				"sNext": "下頁",
				"sLast": "末頁"
			},
			"oAria": {
				"sSortAscending": ": 以升序排列此列",
				"sSortDescending": ": 以降序排列此列"
			}
		}
    } );
} );

查看結果

服務器模式
在瀏覽器調試窗口,我們可以看到發送到后台的參數(即上面ajax請求中d的數據):

draw:1	//確保Ajax從服務器返回的是對應的,服務器接收到此參數后再返回
columns[0][data]:id
columns[0][name]:
columns[0][searchable]:true
columns[0][orderable]:true
columns[0][search][value]:
columns[0][search][regex]:false
columns[1][data]:name
columns[1][name]:
columns[1][searchable]:true
columns[1][orderable]:true
columns[1][search][value]:
columns[1][search][regex]:false
columns[2][data]:countryCode
columns[2][name]:
columns[2][searchable]:true
columns[2][orderable]:true
columns[2][search][value]:
columns[2][search][regex]:false
columns[3][data]:district
columns[3][name]:
columns[3][searchable]:true
columns[3][orderable]:true
columns[3][search][value]:
columns[3][search][regex]:false
columns[4][data]:population
columns[4][name]:
columns[4][searchable]:true
columns[4][orderable]:true
columns[4][search][value]:
columns[4][search][regex]:false
order[0][column]:0	//告訴后台那些列是需要排序的
order[0][dir]:asc	//告訴后台列排序的方式, desc 降序 asc 升序
start:0	//第一條數據的起始位置,比如0代表第一條數據
length:10	//告訴服務器每頁顯示的條數
search[value]:	//全局的搜索條件,此demo為空
search[regex]:false	//為true代表全局搜索的值是作為正則表達式處理

服務器返回的數據

{
    "recordsFiltered": 4079,	//過濾后的記錄數
    "data": [	//表格中需要顯示的數據。
        {
            "countryCode": "AFG",
            "district": "Kabol",
            "name": "Kabul",
            "id": 1,
            "population": 1780000
        },
        {
            "countryCode": "AFG",
            "district": "Qandahar",
            "name": "Qandahar",
            "id": 2,
            "population": 237500
        },
        {
            "countryCode": "AFG",
            "district": "Herat",
            "name": "Herat",
            "id": 3,
            "population": 186800
        },
        {
            "countryCode": "AFG",
            "district": "Balkh",
            "name": "Mazar-e-Sharif",
            "id": 4,
            "population": 127800
        },
        {
            "countryCode": "NLD",
            "district": "Noord-Holland",
            "name": "Amsterdam",
            "id": 5,
            "population": 731200
        },
        {
            "countryCode": "NLD",
            "district": "Zuid-Holland",
            "name": "Rotterdam",
            "id": 6,
            "population": 593321
        },
        {
            "countryCode": "NLD",
            "district": "Zuid-Holland",
            "name": "Haag",
            "id": 7,
            "population": 440900
        },
        {
            "countryCode": "NLD",
            "district": "Utrecht",
            "name": "Utrecht",
            "id": 8,
            "population": 234323
        },
        {
            "countryCode": "NLD",
            "district": "Noord-Brabant",
            "name": "Eindhoven",
            "id": 9,
            "population": 201843
        },
        {
            "countryCode": "NLD",
            "district": "Noord-Brabant",
            "name": "Tilburg",
            "id": 10,
            "population": 193238
        }
    ],
    "draw": 1,	//Datatables發送的draw是多少那么服務器就返回多少
    "recordsTotal": 4079	//數據庫里總共記錄數
}

點此查看更多服務器處理參數。

小結

DataTables是一個表格插件。既可以一次性獲取大量數據在前端做分頁處理(一般不推薦,數據量較大時客戶端壓力大,處理慢),也可以使用服務器處理分頁(只返回當前頁面的數據)。

常用的參數可能就那么幾個,我們可以直接使用它們,也可以自己封裝參數,比如"search[value]"我們可以改成"keyword"再傳給后台,"order[0][column]"可以先在前端轉換成對應"orderColumn"再傳入后台,還可以加上其它特定的業務參數等。

其他一些未提及的,比如服務器模式的自定義回調函數,勇敢的去官網或google探索吧。

總體感覺,使用簡單,配置靈活。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM