Datatables是一款jquery表格插件。它是一個高度靈活的工具,能夠將任何HTML表格添加高級的交互功能。
詳細學習請參考其官網:http://datatables.net/中文網:http://dt.thxopen.com/php
下面是我學習datatables寫的一個服務器端分頁例子,首先,上圖:css
二、接着是js代碼了
2.1顯示初始化datatables,並撰寫刪除修改增長記錄這幾個功能按鈕函數html
function initTable () { var table = $("#example").DataTable({ "paging":true, "pagingType":"full_numbers", "lengthMenu":[5,10,25,50], "processing": true, "searching": true, //是否開啓搜索 "serverSide": true,//開啓服務器獲取數據 "order": [[ 0, "desc" ]], //默認排序 "ajax":{ // 獲取數據 "url":"server.php", "dataType":"json" //返回來的數據形式 }, "columns":[ //定義列數據來源 {'title':"id",'data':"teacher_id"}, {'title':"name",'data':"teacher_name"}, {'title':"pwd",'data':"teacher_password"},//隱藏 {'title':"email",'data':"teacher_email"}, {'title':"date",'data':"teacher_date"}, {'title':"note",'data':"teacher_note"}, {'title':"action",'data':null,'class':"align-center"} // 自定義列 ], "columnDefs": [ //自定義列 { "targets": -1, //改寫哪一列 "data": "teacher_id", "render": function(data, type, row) { // return "<a href='"+full.teacher_id+"'>look at my href</a>"; var html = "<button class='btn btn-info' onclick='edit("+row.teacher_id+")'>修改</button>" + " <button name='btn-del' class='btn btn-danger' onclick='del("+row.teacher_id+")'>刪除</button>"; return html; } }, { "targets":2, "visible":false //隱藏列 }, { "targets":[-1,-2], "orderable":false //禁止排序 }, { "targets":[-1,-3], "searchable":false //禁止搜索 } ], "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": ": 以降序排列此列" } }, "createdRow":function(row,data,index){ //行回調函數 if(data.teacher_id % 2 == 0){ $('td',row).eq(0).css({"color":"#00A8FF","font-weight":"bold"}); } } });//table end return table; } //inintTable END // 刪除 function del(id){ if(confirm('你肯定要刪除 id='+id+' 的記錄?')){ // 肯定 var jsonData={ "id":id }; $.ajax({ type:"get", url:"del.php", data:jsonData, dataType:"json", success:function(msg){ // var msg = eval(msg); if(msg.status == true){ alert("刪除 id= "+msg.id+"成功"); // 刷新table // oTable.fnReloadAjax(); //1.9以前 oTable.ajax.reload(); //1.10以後 // oTable.draw(); }else{ alert("刪除失敗"); } }, error: function(error){ console.log(error); } }); }else{ // 取消 return ; } } //增長 function add () { // console.log("add action"); var jsonData={ "name":$("#add_name").val(), "pwd":$("#add_pwd").val(), "email":$("#add_email").val(), "date":$("#add_date").val(), "note":$("#add_note").val() }; $.ajax({ type:'get', url:'add.php', data:jsonData, dataType:"json", success:function(msg){ if(msg.status == true){ alert("添加成功"); oTable.ajax.reload(); }else{ alert("添加失敗"); } }, error:function(error){ console.log(error); } }); } // 修改 function edit(id){ alert("修改 id = "+id); }
2.2 而後在頁面加載完畢後開啓datatables功能,並增長每列搜索的input框mysql
$(function(){ // oTable 全局變量 oTable = initTable(); // 每列搜索框 /*$("#search li").each(function(){ var title = $('#example thead th').eq( $(this).index() ).text(); $(this).html(title+'<input type="text" placeholder="Search '+title+'" class="form-control"/>'); }); $("#search li").each(function(index){ $(this).find('input').on( 'keyup change', function () { oTable .column(index) .search( this.value ) .draw(); } ); });*/ // Setup - add a text input to each footer cell $('#example tfoot th').each( function (index) { if(index == 3 || index == 5){return;}//隱藏某一列input var title = $('#example thead th').eq( $(this).index() ).text(); $(this).html( '<input type="text" placeholder="Search '+title+'" class="form-control"/>' ); } ); // Apply the search oTable.columns().eq( 0 ).each( function ( colIdx ) { $( 'input', oTable.column( colIdx ).footer() ).on( 'keyup change', function () { oTable .column( colIdx ) .search( this.value ) .draw(); } ); } ); });//jquery end
三、最後說server.php代碼
基本思想就是接收傳過來的參數,而後對參數進行處理,編寫sql語句,而後取出當頁數據返回頁面。
傳遞過來的參數能夠用firefox查看:jquery
<?php header("Content-type: text/html;charset=utf-8");//防止亂碼 //一、獲取連接 $conn=@mysql_connect("localhost","root",""); if(!$conn){ //mysql_error()是返回mysql的上一次操做 die("鏈接失敗".mysql_error()); }else{ //echo '鏈接成功!<br/>'; } //二、選擇對應的數據庫 @mysql_select_db("etemsdb"); //三、設置操做編碼(無關緊要,建議有) mysql_query("set names utf8");//保證是按照utf8碼操做的【utf8無-的,有-的是網頁版的!!!!!!!】 $draw = $_GET['draw']; //第幾回請求 //排序 $order_column = $_GET['order']['0']['column']; // 哪一列排序 $order_dir= $_GET['order']['0']['dir']; // ase desc 升序或者降序 //拼接排序sql $orderSql = ""; if(isset($order_column)){ $i = intval($order_column); switch($i){ case 0;$orderSql = " order by teacher_id ".$order_dir;break; case 1;$orderSql = " order by teacher_name ".$order_dir;break; // case 2;$orderSql = " order by teacher_password ".$order_dir;break; case 2;$orderSql = " order by teacher_email ".$order_dir;break; case 3;$orderSql = " order by teacher_date ".$order_dir;break; case 4;$orderSql = " order by teacher_note ".$order_dir;break; default;$orderSql = ''; } } //分頁 $start = $_GET['start'];//從多少開始 $length = $_GET['length'];//數據長度 $limitSql = ''; $limitFlag = isset($_GET['start']) && $length != -1 ; if ($limitFlag ) { $limitSql = " LIMIT ".intval($start).", ".intval($length); } //定義查詢數據總記錄數sql $sumSql = "SELECT count(teacher_id) as sum FROM teacher"; //條件過濾後記錄數 必要 $recordsFiltered = 0; //表的總記錄數 必要 $recordsTotal = 0; $recordsTotalResult = mysql_query($sumSql,$conn); while($row=mysql_fetch_assoc($recordsTotalResult)){ $recordsTotal = $row['sum']; } //搜索//定義過濾條件查詢過濾後的記錄數sql $search = $_GET['search']['value'];//獲取前臺傳過來的過濾條件 // 每列搜索 $j = 1; $search_arr =array(); $colSearchSql=''; for($j=0;$j<6;$j++){ $colSearchable = $_GET['columns'][$j]['searchable']; $colSearchVal = $_GET['columns'][$j]['search']['value']; if(strlen($colSearchVal)>0 && $colSearchable == 'true' ){ switch ($j) { case 0: $colSearchVal = "teacher_id LIKE '%".$colSearchVal."%'"; array_push($search_arr,$colSearchVal); break; case 1: $colSearchVal = "teacher_name LIKE '%".$colSearchVal."%'"; array_push($search_arr,$colSearchVal); break; case 2: $colSearchVal = "teacher_password LIKE '%".$colSearchVal."%'"; array_push($search_arr,$colSearchVal); break; case 3: $colSearchVal = "teacher_email LIKE '%".$colSearchVal."%'"; array_push($search_arr,$colSearchVal); break; case 4: $colSearchVal = "teacher_date LIKE '%".$colSearchVal."%'"; array_push($search_arr,$colSearchVal); break; case 5: $colSearchVal = "teacher_note LIKE '%".$colSearchVal."%'"; array_push($search_arr,$colSearchVal); break; default: # code... break; } } } if(empty($search_arr) == false){ $colSearchSql = " WHERE ".implode(" AND ",$search_arr); } // 綜合搜索sql // $zSearchSql =" where teacher_id || teacher_name || teacher_password || teacher_email || teacher_date || teacher_note LIKE '%".$search."%'"; $zSearchSql = " teacher_id LIKE '%".$search."%' OR teacher_name LIKE '%".$search."%' OR teacher_email LIKE '%".$search."%' OR teacher_date LIKE '%".$search."%' OR teacher_note LIKE '%".$search."%'"; // 拼接搜索SQL $sumSearchSql = ''; if(strlen($colSearchSql)>0 && strlen($search)>0){ $sumSearchSql = $colSearchSql." AND (".$zSearchSql.")"; }else if(strlen($colSearchSql)>0 && strlen($search)==0){ $sumSearchSql = $colSearchSql; }else if(strlen($colSearchSql)==0 && strlen($search)>0){ $sumSearchSql = " WHERE ".$zSearchSql; }else{ $sumSearchSql = ''; } if(strlen($sumSearchSql)>0){ $recordsFilteredResult = mysql_query($sumSql.$sumSearchSql); while ($row = mysql_fetch_assoc($recordsFilteredResult)) { $recordsFiltered = $row['sum']; } }else{ $recordsFiltered = $recordsTotal; } // query data $sql=''; $totalResultSql = "SELECT * FROM teacher"; $infos = array(); // 拼接最終SQL $sql=$totalResultSql.$sumSearchSql.$orderSql.$limitSql; $dataResult = mysql_query($sql,$conn); while ($row = mysql_fetch_assoc($dataResult)) { // $obj = array($row['teacher_id'], $row['teacher_name'], $row['teacher_password'], $row['teacher_email'], $row['teacher_date'], $row['teacher_note']); // array_push($infos,$obj); array_push($infos,$row); } // return data echo json_encode(array( "draw" => $draw, "recordsTotal" =>$recordsTotal, // necessary "recordsFiltered" =>$recordsFiltered, // necessary "data" =>$infos // necessary ),JSON_UNESCAPED_UNICODE);
刪除記錄del.php ,增長記錄add.php代碼ajax
<?php // 刪除記錄 $conn=@mysql_connect("localhost","root",""); //數據庫 @mysql_select_db("etemsdb"); //數據表 $id=$_GET['id']; $sql = "DELETE FROM `teacher` WHERE teacher_id = ".$id; $res = mysql_query($sql,$conn); if($res){ echo json_encode(array( "status"=>true, // "data"=>"this is data~", "id"=>$id ),JSON_UNESCAPED_UNICODE); }else{ echo json_encode(array( "status"=>false, // "data"=>"this is data~", "id"=>$id ),JSON_UNESCAPED_UNICODE); }
<?php // 增長記錄 $conn=@mysql_connect("localhost","root",""); //數據庫 @mysql_select_db("etemsdb"); //數據表 $name=$_GET['name']; $pwd=$_GET['pwd']; $email=$_GET['email']; $date=$_GET['date']; $note=$_GET['note']; $sql="INSERT INTO teacher ( `teacher_name`, `teacher_password`, `teacher_email`, `teacher_date`, `teacher_note`) VALUES ('".$name."',md5('".$pwd."'),'".$email."','".$date."','".$note."')"; $res=mysql_query($sql,$conn); if($res){ echo json_encode(array( "status"=>true, "info"=>"add success" ),JSON_UNESCAPED_UNICODE); }else{ echo json_encode(array( "status"=>false, "info"=>"add error", "sql"=>$sql ),JSON_UNESCAPED_UNICODE); }
參考文檔: datatables服務器端分頁:http://www.qdfuns.com/notes/16811/278151cce7baf16d3c7ed8e830dde70e.html 支持ajax php搜索分頁,可見附件sql
中文官網安裝使用手冊:http://datatables.club/manual/install.html 數據庫
datatable+bootstrap 表格分頁實例 :http://runjs.cn/detail/ejbscmytjson
附件: 連接:http://pan.baidu.com/s/1jIa4Gq6 密碼:13nsbootstrap