什么是服务器模式?
是不是发现在处理太多 DOM 数据或者 AJAX 一次性把数据获得后,DataTables 表现的不是很满意?这是肯定的, 因为 DT 需要渲染,创建 tr/td ,所以数据越多,速度就越慢。 为了解决这个问题 DataTables 提供了 服务器模式,把本来客户端所做的事情交给服务器去处理, 比如排序(order)、分页(paging)、过滤(filter)。对于客户端来说这些操作都是比较消耗资源的, 所以打开服务器模式后不用担心这些操作会影响到用户体验。
当你打开服务器模式的时候,每次绘制表格的时候,DataTables 会给服务器发送一个请求(包括当前分页,排序,搜索参数等等)。DataTables 会向 服务器发送 一些参数 去执行所需要的处理,然后在服务器组装好 相应的数据 返回给 DataTables。
开启服务器模式需要使用 serverSideOption和 ajaxOption ajax不定时一讲选项,进一步的信息,请参考下面的 配置选项。
如何开启服务器模式(Configuration)
使用服务器模式需要启用 serverSideOption选项 , 设置为 true,并且配置 ajaxOption ajax不定时一讲设置url,告诉 DataTables 该 从那里获得数据
|
1
2
3
4
5
6
|
$('#example').DataTable( {
//开启服务器模式
serverSide: true,
//数据来源(包括处理分页,排序,过滤) ,即url,action,接口,等等
ajax: '/data-source'
} ); |
ajaxOption ajax不定时一讲 可以直接接受一个字符串也可以作为一个对象使用。作为对象他就像 jQuery.ajax 配置一样
post方式发送的请求,代码如下 |
1
2
3
4
5
6
7
|
$('#example').DataTable( {
serverSide: true,
ajax: {
url: '/data-source',
type: 'POST'
}
} ); |
在 DataTables 中的 ajax选项配置详细参考 ajaxOption ajax不定时一讲
老版(Legacy)
1.9-版中发送给服务器的参数和 1.10+的有所不同。但是Datatables为1.9-的脚本做了兼容模式, 你可以使用高版本的js兼容低版本的写法,但是反过来则不行。 旧的是使用 sAjaxSource 而新的是使用 ajaxOption ajax不定时一讲或者通过设置 0.fn.dataTable.ext.legacy.ajax = true;
1.9版本服务器操作的文档看请 参考这里
服务器模式示例数据格式(Example data)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
{ "draw": 1,
"recordsTotal": 57,
"recordsFiltered": 57,
"data": [
[
"Angelica",
"Ramos",
"System Architect",
"London",
"9th Oct 09",
"$2,875"
],
[
"Ashton",
"Cox",
"Technical Author",
"San Francisco",
"12th Jan 09",
"$4,800"
],
...
]
} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
{ "draw": 1,
"recordsTotal": 57,
"recordsFiltered": 57,
"data": [
{
"name":"Angelica",
"age":"Ramos",
"office":"System Architect",
"address":"London",
"date":"9th Oct 09",
"salary":"$2,875"
},
{
"name":"Ashton",
"age":"Cox",
"office":"Technical Author",
"address":"San Francisco",
"date":"12th Jan 09",
"salary":"$4,800"
},
...
]
} |
|
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
31
32
|
{ "draw": 1,
"recordsTotal": 57,
"recordsFiltered": 57,
"data": [
{
"DT_RowId": "row_3",
"DT_RowData": {
"pkey": 3
},
"first_name": "Angelica",
"last_name": "Ramos",
"position": "System Architect",
"office": "London",
"start_date": "9th Oct 09",
"salary": "$2,875"
},
{
"DT_RowId": "row_17",
"DT_RowData": {
"pkey": 17
},
"first_name": "Ashton",
"last_name": "Cox",
"position": "Technical Author",
"office": "San Francisco",
"start_date": "12th Jan 09",
"salary": "$4,800"
},
...
]
} |