Data sources 数据源
DataTables可以从四种基本形式的数据源获取数据:
HTML document (DOM)
Javascript (array / objects)
Ajax sourced data with client-side processing
Ajax sourced data with server-side processing
1、在html表格数据上应用DateTables
$(document).ready(function() {
$('#example').dataTable();
} );
2、ajax数据
$(document).ready(function() {
$('#example').dataTable( {
"ajax": '../ajax/data/arrays.txt'
} );
} );
3、js数据,例子是用一个js数组初始化dt数据
var dataSet = [
['Trident','Internet Explorer 4.0','Win 95+','4','X'],
['Trident','Internet Explorer 5.0','Win 95+','5','C'],
['Trident','Internet Explorer 5.5','Win 95+','5.5','A'],
['Trident','Internet Explorer 6','Win 98+','6','A'],
['Trident','Internet Explorer 7','Win XP SP2+','7','A'],
['Trident','AOL browser (AOL desktop)','Win XP','6','A'],
['Gecko','Firefox 1.0','Win 98+ / OSX.2+','1.7','A'],
['Gecko','Firefox 1.5','Win 98+ / OSX.2+','1.8','A'],
['Gecko','Firefox 2.0','Win 98+ / OSX.2+','1.8','A'],
['Gecko','Firefox 3.0','Win 2k+ / OSX.3+','1.9','A'],
['Gecko','Camino 1.0','OSX.2+','1.8','A'],
['Gecko','Camino 1.5','OSX.3+','1.8','A'],
['Gecko','Netscape 7.2','Win 95+ / Mac OS 8.6-9.2','1.7','A'],
['Gecko','Netscape Browser 8','Win 98SE+','1.7','A'],
['Gecko','Netscape Navigator 9','Win 98+ / OSX.2+','1.8','A'],
['Gecko','Mozilla 1.0','Win 95+ / OSX.1+',1,'A'],
['Gecko','Mozilla 1.1','Win 95+ / OSX.1+',1.1,'A'],
['Gecko','Mozilla 1.2','Win 95+ / OSX.1+',1.2,'A'],
['Gecko','Mozilla 1.3','Win 95+ / OSX.1+',1.3,'A'],
['Gecko','Mozilla 1.4','Win 95+ / OSX.1+',1.4,'A'],
['Gecko','Mozilla 1.5','Win 95+ / OSX.1+',1.5,'A'],
['Gecko','Mozilla 1.6','Win 95+ / OSX.1+',1.6,'A'],
['Gecko','Mozilla 1.7','Win 98+ / OSX.1+',1.7,'A'],
['Gecko','Mozilla 1.8','Win 98+ / OSX.1+',1.8,'A'],
['Gecko','Seamonkey 1.1','Win 98+ / OSX.2+','1.8','A'],
['Gecko','Epiphany 2.20','Gnome','1.8','A'],
['Webkit','Safari 1.2','OSX.3','125.5','A'],
['Webkit','Safari 1.3','OSX.3','312.8','A'],
['Webkit','Safari 2.0','OSX.4+','419.3','A'],
['Webkit','Safari 3.0','OSX.4+','522.1','A'],
['Webkit','OmniWeb 5.5','OSX.4+','420','A'],
['Webkit','iPod Touch / iPhone','iPod','420.1','A'],
['Webkit','S60','S60','413','A'],
['Presto','Opera 7.0','Win 95+ / OSX.1+','-','A'],
['Presto','Opera 7.5','Win 95+ / OSX.2+','-','A'],
['Presto','Opera 8.0','Win 95+ / OSX.2+','-','A'],
['Presto','Opera 8.5','Win 95+ / OSX.2+','-','A'],
['Presto','Opera 9.0','Win 95+ / OSX.3+','-','A'],
['Presto','Opera 9.2','Win 88+ / OSX.3+','-','A'],
['Presto','Opera 9.5','Win 88+ / OSX.3+','-','A'],
['Presto','Opera for Wii','Wii','-','A'],
['Presto','Nokia N800','N800','-','A'],
['Presto','Nintendo DS browser','Nintendo DS','8.5','C/A<sup>1</sup>'],
['KHTML','Konqureror 3.1','KDE 3.1','3.1','C'],
['KHTML','Konqureror 3.3','KDE 3.3','3.3','A'],
['KHTML','Konqureror 3.5','KDE 3.5','3.5','A'],
['Tasman','Internet Explorer 4.5','Mac OS 8-9','-','X'],
['Tasman','Internet Explorer 5.1','Mac OS 7.6-9','1','C'],
['Tasman','Internet Explorer 5.2','Mac OS 8-X','1','C'],
['Misc','NetFront 3.1','Embedded devices','-','C'],
['Misc','NetFront 3.4','Embedded devices','-','A'],
['Misc','Dillo 0.8','Embedded devices','-','X'],
['Misc','Links','Text only','-','X'],
['Misc','Lynx','Text only','-','X'],
['Misc','IE Mobile','Windows Mobile 6','-','C'],
['Misc','PSP browser','PSP','-','C'],
['Other browsers','All others','-','-','U']
];
$(document).ready(function() {
$('#demo').html( '<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>' );
$('#example').dataTable( {
"data": dataSet,
"columns": [
{ "title": "Engine" },
{ "title": "Browser" },
{ "title": "Platform" },
{ "title": "Version", "class": "center" },
{ "title": "Grade", "class": "center" }
]
} );
} );
4、服务器端过程
有很多方法可以把数据装进dataTables里,如果你正在使用一个很庞大的数据库进行工作,你可以考虑使用dataTables提供的服务器端选项,开启服务器端进程后,所有的分页、搜索、排序行为都会被服务器端接手,服务器端的sql引擎(类似这么个意思)就可以在大量数据上进行这些操作(毕竟数据库引擎才是为这项工作而生的)。如此,表格里的每一行会用新的ajax请求来获取它所需的信息。
服务器端过程打开方法:把选项serverSide设为true,然后用ajax选项提交一份ajax数据,例子展示了一个简单的表格,这个例子用的是服务器端过程。更复杂的用法看后面对服务器端过程使用的详细介绍。
eg:---------------------
$(document).ready(function() {
$('#example').dataTable( {
"processing": true,
"serverSide": true,
"ajax": "../server_side/scripts/server_processing.php"
} );
} );
=============下面是API:============================================
===================================================================
Add rows 添加行
新的行可以用 row.add方法,多行数据可以使用rows.add方法,注意想要看到新加的行需要使用draw() 方法,这个方法是dataTables在发生变化时调用的,很容易使用。
下面例子展示了每次单击按钮添加一行的功能。
$(document).ready(function() {
var t = $('#example').DataTable();
var counter = 1;
$('#addRow').on( 'click', function () {
t.row.add( [
counter +'.1',
counter +'.2',
counter +'.3',
counter +'.4',
counter +'.5'
] ).draw();
counter++;
} );
// Automatically add a first row of data
$('#addRow').click();
} );
规定搜索功能仅对某一列有效
dt提供的搜索功能很有用,它可以让你迅速搜索表格里的信息,但是它的作用范围是整个表格的所有数据,有时候我们可能只想在某个单独的列使用搜索用能,DataTables提供了这个功能,使用column().search()方法可以指定搜索结果是来自哪一列的。列的搜索是可以相互累加的,你可以进行多列的搜索,给用户提供更多复杂的搜索功能。
This examples shows text elements being used with the column().search()DT method to add input controls in the footer of the table for each column. Note that the *index*:visible option is used for the column selector to ensure that the column()DT method takes into account any hidden columns when selecting the column to act upon.
code:-----------------------
$(document).ready(function() {
// Setup - add a text input to each footer cell
$('#example tfoot th').each( function () {
var title = $('#example thead th').eq( $(this).index() ).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
} );
// DataTable
var table = $('#example').DataTable();
// Apply the search
table.columns().every( function () {
var that = this;
$( 'input', this.footer() ).on( 'keyup change', function () {
that
.search( this.value )
.draw();
} );
} );
} );
高亮显示列Highlighting rows and columns
//Highlighting rows and columns have be quite useful for drawing attention to where the user's cursor is in a table, particularly if you have a lot of narrow columns. Of course the highlighting of a row is easy enough using CSS, but for column highlighting, you need to use a little bit of Javascript.
//This example shows that in action on DataTable by making use of the cell().index()DT method to get the index of the column that is to be operated on, and then the cells().nodes()DT and column().nodes()DT methods to remove old classes and apply the new highlighted class, respectively.
//----------------------------------
$(document).ready(function() {
var lastIdx = null;
var table = $('#example').DataTable();
$('#example tbody')
.on( 'mouseover', 'td', function () {
var colIdx = table.cell(this).index().column;
if ( colIdx !== lastIdx ) {
$( table.cells().nodes() ).removeClass( 'highlight' );
$( table.column( colIdx ).nodes() ).addClass( 'highlight' );
}
} )
.on( 'mouseleave', function () {
$( table.cells().nodes() ).removeClass( 'highlight' );
} );
} );
Child rows (show extra / detailed information) 子行(http://datatables.net/examples/api/row_details.html)
给一个行添加下级子行,用于展示额外信息。
The example below makes use of the row().childDT methods to firstly check if a row is already displayed, and if so hide it (row().child.hide()DT), otherwise show it (row().child.show()DT). The content of the child row is, in this example, defined by the formatDetails() function, but you would replace that with whatever you wanted to show the content required, possibly including, for example, an Ajax call to the server to obtain the extra information to show.
/* Formatting function for row details - modify as you need */
function format ( d ) {
// `d` is the original data object for the row
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
'<tr>'+
'<td>Full name:</td>'+
'<td>'+d.name+'</td>'+
'</tr>'+
'<tr>'+
'<td>Extension number:</td>'+
'<td>'+d.extn+'</td>'+
'</tr>'+
'<tr>'+
'<td>Extra info:</td>'+
'<td>And any further details here (images etc)...</td>'+
'</tr>'+
'</table>';
}
$(document).ready(function() {
var table = $('#example').DataTable( {
"ajax": "../ajax/data/objects.txt",
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "salary" }
],
"order": [[1, 'asc']]
} );
// Add event listener for opening and closing details
$('#example tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
} );
} );
Row selection (multiple rows) (多)行的选取,这个有点类似checkbox的功能
rows().data() 通过点击事件添加和移除选中状态。
例子:count选中的行数
$(document).ready(function() {
var table = $('#example').DataTable();
$('#example tbody').on( 'click', 'tr', function () {
$(this).toggleClass('selected');
} );
$('#button').click( function () {
alert( table.rows('.selected').data().length +' row(s) selected' );
} );
} );
Row selection and deletion (single row) 行的选取,只能选择一行,有点类似 input[type=radio]
示例展示了一个修改表格内容的例子,每次只有一行可以被选中,它所作的操作是检测当前的目标行,如果已经选中则取消选择,如果没有则取消其他行的选择并选择当前行。使用row().delete()方法删除行,使用draw()方法,它的第一个参数设为false ,这会重新拉取表格数据而保持在当前页不变。(如果没有这个参数,删除数据后分页会跳回第一页)
更多选择行并进行各种操作的复杂的用法看这里http://datatables.net/extensions/tabletools/
例子:
$(document).ready(function() {
var table = $('#example').DataTable();
$('#example tbody').on( 'click', 'tr', function () {
if ( $(this).hasClass('selected') ) {
$(this).removeClass('selected');
}
else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
} );
$('#button').click( function () {
table.row('.selected').remove().draw( false );
} );
} );
Form inputs 表单输入
为了实现分页、排序、搜索等功能,DataTables会将不需要展示的行和单元格从当前DOM移除,这么做提升了性能和兼容性,但是这意味着提交一个跨几个分页点表单会有点问题,需要我们进行一些额外的工作来获取不在当前页面的信息。
DT的$()方法可以用于获取文档的内容而不用考虑分页、排序带来的问题。下面例子展示了用$()获取表格中所有输入数据。
code:-----------------------
$(document).ready(function() {
var table = $('#example').DataTable();
$('button').click( function() {
var data = table.$('input, select').serialize();
alert(
"The following data would have been submitted to the server:
"+
data.substr( 0, 120 )+'...'
);
return false;
} );
} );
Index Column 索引列
高交互性的表格经常需要一个‘counter’来标记每一行处的位置,这一行是不支持排序的,并且随着数据的动态变化每个索引对应的行会动态变化。
例子展示了DataTables是如何实现这个功能的,第一列是counter列,并且搜索和排序时会动态更新。这是通过监听表格的order和search事件实现的,当检测到这些事件的发生时,column().nodes()方法被调用用于获取目标列的TH/TD指针,each()方法迭代每一行数据并给他们设置所需的不同内容。
filter和order选项通过当前生效的filter被用于cloumn()方法来获取当前排序的指针。(翻译的有点问题,看原文:http://datatables.net/examples/api/counter_columns.html)
code:-----------------------
$(document).ready(function() {
var t = $('#example').DataTable( {
"columnDefs": [ {
"searchable": false,
"orderable": false,
"targets": 0
} ],
"order": [[ 1, 'asc' ]]
} );
t.on( 'order.dt search.dt', function () {
t.column(0, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
cell.innerHTML = i+1;
} );
} ).draw();
} );
动态显示和隐藏行 Show / hide columns dynamically
例子展示了怎么使用column().visible()方法去动态显示和隐藏一个列。这个例子还设置了滚动,只是为了展示滚动在这里被支持,但它并不是必须的。
另外,几个列可以同时被隐藏和显示,只需使用columns()方法选中多列,再用columns().visible()方法设置可见性状态。
If you are looking for a more complete column visibility interaction controls ColVis for DataTables
provides a complete interface for allowing the user to show and hide columns in the table.
如果你需要更加详细的列显示状态交互,DataTables的ColVis (http://datatables.net/extensions/colvis/)提供了一些完整的接口来控制列的显示和隐藏。
$(document).ready(function() {
var table = $('#example').DataTable( {
"scrollY": "200px",
"paging": false
} );
$('a.toggle-vis').on( 'click', function (e) {
e.preventDefault();
// Get the column API object
var column = table.column( $(this).attr('data-column') );
// Toggle the visibility
column.visible( ! column.visible() );
} );
} );
Using API in callbacks 在回调方法中使用api
有时候你也许需要在dt回调方法(例如:initComplete, roeCallback 等)里面使用api,但是这有一个问题就是对象并没有完全初始化完,所以你无法把结果赋给一个值并在回调里面使用,但是,所有的dt回调是在dt实例里面完成的,所以你可以使用javascript的特殊变量this来获取,this.api() 会获取一个指向表格的api实例。
在这个例子中,$() 方法被用来获取表格中所有的单元格指针,然后给他们添加了一些行为(例子中是一个点击事件),在这边所做的是给表格加了一个filter(搜索),每次点击每个单元格,里面的值会被用作搜索框里的参数过滤数据。其实这也并没有什么,我们可以在在表格加载完毕时给它添加一个delegate事件来实现同样的功能,这里只是为了展示如何在callback里面使用api;
$(document).ready(function() {
$('#example').dataTable( {
"initComplete": function () {
var api = this.api();
api.$('td').click( function () {
api.search( this.innerHTML ).draw();
} );
}
} );
} );
Ajax---------------
从嵌套的json数据获取表格数据列
$(document).ready(function() {
$('#example').dataTable( {
"processing": true,
"ajax": "data/objects_deep.txt",
"columns": [
{ "data": "name" },
{ "data": "hr.position" },
{ "data": "contact.0" },
{ "data": "contact.1" },
{ "data": "hr.start_date" },
{ "data": "hr.salary" }
]
} );
} );
------------------------------
{
"data": [
{
"name": "Tiger Nixon",
"hr": {
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25"
},
"contact": [
"Edinburgh",
"5421"
]
},
{
"name": "Garrett Winters",
"hr": {
"position": "Accountant",
"salary": "$170,750",
"start_date": "2011/07/25"
},
"contact": [
"Tokyo",
"8422"
]
}]
}
从嵌套的数组获取数据
$(document).ready(function() {
$('#example').dataTable( {
"ajax": "data/objects_subarrays.txt",
"columns": [
{ "data": "name[, ]" },
{ "data": "hr.0" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "hr.2" },
{ "data": "hr.1" }
]
} );
} );
{
"name": [
"Nixon",
"Tiger"
],
"hr": [
"System Architect",
"$3,120",
"2011/04/25"
],
"office": "Edinburgh",
"extn": "5421"
}
//Name列是从一个包含两个元素的name数组里获取的,展示时数组中的元素会自动被串联起来,name[,]括号里面的分隔符会被用做连接数组元素的连接符。
//下面的hr.1 hr.2直接通过数组下标获取单独的数组元素。
在列里生成额外内容
// columns.renderDT for content that is dynamic (i.e. based upon the row's data)
// columns.defaultContentDT for static content (i.e. simple strings)
$(document).ready(function() {
var table = $('#example').DataTable( {
"ajax": "data/arrays.txt",
"columnDefs": [ {
"targets": -1,
"data": null,
"defaultContent": "<button>Click!</button>"
} ]
} );
$('#example tbody').on( 'click', 'button', function () {
var data = table.row( $(this).parents('tr') ).data();
alert( data[0] +"'s salary is: "+ data[ 5 ] );
} );
} );
// 在每列加了一个按钮,并添加了显示行内信息的点击事件。
//自定义数据源参数 Custom data source property
//当从ajax获取数据时,dt会默认读取'data'参数,(它假设默认你的json是这样子的 { "data": [...] }),如果你使用的参数不是'data'而是别的,可以使用dataSrc选项来自定义。
// 它有几种使用方法 1、dataSrc:"myDataName" , 传递一个字符串,告诉他我们的数据是 { "myDataName": [...] }; 2、dataSrc:'' ,空字符串,说明数据不是对象,是一个数组;3、dataSrc: function(json) {}) ,dataSrc为一个方法,这个方法可以返回我们需要的数据形式,比如ni可以在这个方法里读取一个xml文件并返回我们需要的json格式数据。
$(document).ready(function() {
$('#example').dataTable( {
"ajax": {
"url": "data/arrays_custom_prop.txt",
"dataSrc": "demo"
}
} );
} );
-----------------------------------------------
$(document).ready(function() {
$('#example').dataTable( {
"ajax": {
"url": "data/objects_root_array.txt",
"dataSrc": ""
},
"columns": [
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "extn" },
{ "data": "start_date" },
{ "data": "salary" }
]
} );
} );
//Deferred rendering for speed
//When deferred rendering is enabled, rather than having DataTables create all TR and TD nodes required for the table when the data is loaded, DataTables will only create the nodes required for each individual row at the time of that row being drawn on the page (these nodes are then retained in case they are needed again so they aren't created multiple times). This can give a significant performance increase, since a lot less work is done at initialisation time.
--------------------------------------
$(document).ready(function() {
$('#example').dataTable( {
"ajax": "data/arrays.txt",
"deferRender": true
} );
} );
Custom filtering - range search 范围的筛选
$.fn.dataTable.ext.search
--------------------------------------
/* Custom filtering function which will search data in column four between two values */
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var min = parseInt( $('#min').val(), 10 );
var max = parseInt( $('#max').val(), 10 );
var age = parseFloat( data[3] ) || 0; // use data for the age column
if ( ( isNaN( min ) && isNaN( max ) ) ||
( isNaN( min ) && age <= max ) ||
( min <= age && isNaN( max ) ) ||
( min <= age && age <= max ) )
{
return true;
}
return false;
}
);
$(document).ready(function() {
var table = $('#example').DataTable();
// Event listener to the two range filtering inputs to redraw on input
$('#min, #max').keyup( function() {
table.draw();
} );
} );