這個插件很好用,篩選,分頁等功能都是內置的了。重要的是根據自己的喜愛,變換它的css。
本文主要寫個和ajax交互的小例子。
ajax_data.php
<?php
//請求次數
$page = is_numeric($_POST['sEcho']) ? intval($_POST['sEcho']) : 0;
//獲取搜索框輸入值
$search = trim($_POST['sSearch']) ? trim($_POST['sSearch']) : false;
//獲取每頁數據條數
$pagesize = is_numeric($_POST['iDisplayLength']) ? intval($_POST['iDisplayLength']) : 0;
//獲取當前頁起始數據的ID
$offset = is_numeric($_POST['iDisplayStart']) ? intval($_POST['iDisplayStart']) : 0;
//獲取表格中執行排序的列號(每列都包括在內,從0開始)
$sortcol = is_numeric($_POST['iSortCol_0']) ? intval($_POST['iSortCol_0']) : 0;
//獲取表格中執行排序的規則(asc,desc兩者交替變換)
$sortdir = trim($_POST['sSortDir_0']) ? trim($_POST['sSortDir_0']) : false;
mysql_connect('主機名','用戶名','密碼');
mysql_select_db('testdrive');
$sql = "SELECT engine,Browser,Platform,version,grade FROM test_datatable";
$sql .= " where engine like '{$search}%' or Browser like '{$search}%'";
//根據iSortCol_0和sSortDir_0按對應字段排序
switch($sortcol){
case '0':
$sql .= " order by engine {$sortdir}";
break;
case '1':
$sql .= " order by Browser {$sortdir}";
break;
case '2':
$sql .= " order by Platform {$sortdir}";
break;
case '3':
$sql .= " order by version {$sortdir}";
break;
case '4':
$sql .= " order by grade {$sortdir}";
break;
default:
break;
}
$sql .= " limit {$offset},{$pagesize}";
$result = mysql_query($sql);
$data = array();
while( $array=mysql_fetch_assoc($result)){
$data[] = $array;
}
$sql_total = "select count(*) as count from test_datatable";
$sql_total .= " where engine like '{$search}%' or Browser like '{$search}%'";
$result_total = mysql_query($sql_total);
$data_total = mysql_fetch_assoc($result_total);
$reAjaxData['iTotalRecords'] = $data_total['count'];
$reAjaxData['iTotalDisplayRecords'] = $data_total['count'];
$aaData = array();
foreach($data as $key => $value )
{
foreach( $value as $k => $v )
{
$aaData[$key][] = $v;
}
}
$reAjaxData['aaData'] = $aaData;
echo json_encode($reAjaxData);
exit;
?>
說明:
js與php交互使用的參數,其中一個比較特殊的是sEcho,這個參數需要以後原封不動地返回給頁面。
由於默認是以$.getJSON發送請求,所以http命令是GET,參數是以url參數的方式傳遞的。
如果希望以POST命令,以json方式發送請求,而且要加上客戶名稱這個參數,所以這裏需要做些修改。
DataTables通過fnServerData提供了這樣一個接口,fnServerData是與服務器端交換數據時被調用的函數,默認實現是如上所說的通過getJSON發送請求,然後接收特定格式的json數據。
* sSearch是要搜索的詞條
* 瀏覽器清除cookie以及其他網站和插件數據,之後就search爲空,有可能是datatable插件數據緩存了。
ajax拋出的數組名必須是aaData,否則不會被填充到表格內
aaData必須是個二維數組。如果是一位數組,會豎向填充第一列,其他列都爲空
類似這樣的錯誤:DataTables warning(table_id='example'):Requested unknown parameter '4' from the data source for now 0;拋出的數據和表格的數據數量不符
$reAjaxData['aaData'] = array(
0=>array('1','2','3','4','6'),
1=>array('1','2','3','4','5')
);
//如果報錯:DataTables warning(table_id='example'):Requested unknown parameter '0' from the data source for now 0,很有可能數組是關聯數組導致的
//以下數組,關聯數組不能展示數據到表格內
/*{
"aaData": [
{
"engine": "Trident",
"Browser": "Internet Explorer 4.0",
"Platform": "Win 95+",
"version": "4",
"grade": "C"
},
{
"engine": "Trident",
"Browser": "Internet Explorer 5.0",
"Platform": "Win 95+",
"version": "4",
"grade": "C"
}
]
}*/
對datatable對象參數進行部分配置以及說明
jQuery(document).ready(function() {
//alert(typeof(jQuery().dataTable));
//alert('begin');
if (!jQuery().dataTable) {
return;
}
$('#example').dataTable({
//paging:false; //設置paging選項,禁止表格分頁(默認是打開的)
//scrollY: 100; //在表格裏使用滾動,你需要加上scrollY選項
//"sScrollY" : 450, //DataTables的高
//"sScrollX" : 820, //DataTables的寬
//"aaSorting" : [[2, "desc"]]
"sPaginationType": "full_numbers", //分頁風格,full_number會把所有頁碼顯示出來
bFilter: true, //去掉搜索框
//對於從服務器端取數據,要指定以下兩個參數bServerSide和sAjaxSource
"bServerSide": true, //開啓服務器模式,原始的靜態頁面不分頁
//使用ajax源
"sAjaxSource": "ajax_data.php",
/* 從 Ajax 源加載數據的表的內容 如果加"type": "POST",則使用post方式傳遞數據*/
//aoData是以post方式傳遞給php交互的key-value
"fnServerData": function ( sSource, aoData, fnCallback ) {
$.ajax( {
"dataType": 'json',
"type": "POST",
"url": sSource,
"data": aoData,
"success": fnCallback
} );
},
"iDisplayLength": 5, //設置datatables的默認顯示條數
//定義每頁顯示數據數量數組
"aLengthMenu": [
[5,10, 20, 30, 40, -1],
[5,10, 20, 30, 40, "全部"] //每頁變化值 ,默認顯示最後一個元組
],
// 改變語言提示 把原始表示轉換爲中文
"oLanguage": {
"sLengthMenu": "每頁 _MENU_ 條記錄",
"sZeroRecords": "抱歉,沒有找到",
"sInfo": "從 _START_ 到 _END_ / 共 _TOTAL_ 條數據",
"sInfoEmpty": "沒有數據",
"sInfoFiltered": "(從 _MAX_ 條數據中檢索)",
"sSearch":"搜索:",
"oPaginate": {
"sFirst": "首頁",
"sPrevious": "上一頁",
"sNext": "下一頁",
"sLast": "尾頁"
},
"sProcessing": "<img src='loading.gif' />",
},
});
});
index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>DataTables live example</title>
<style type="text/css">
@import "css/demo_page.css";
@import "css/demo_table.css";
</style>
<script type="text/javascript" language="javascript" src="./jquery.js"></script>
<script class="jsbin" src="./jquery.dataTables.nightly.js"></script>
</head>
<body id="dt_example">
<div id="container">
<h1>Live example</h1>
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
<thead>
<tr>
<th>Rendering engine</th>
<th>Browser</th>
<th>Platform(s)</th>
<th>Engine version</th>
<th>CSS grade</th>
</tr>
</thead>
<tbody>
<tr class="odd gradeX">
<td colspan="5">等待加載數據...
</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Rendering engine</th>
<th>Browser</th>
<th>Platform(s)</th>
<th>Engine version</th>
<th>CSS grade</th>
</tr>
</tfoot>
</table>
</div>
<script>
//$(document).ready(function() {
// $('#example').dataTable();
//} );
</script>
<script type="text/javascript" src="showlist.js"></script>
</body>
</html>