您的位置:首页 > 编程语言 > PHP开发

datatables使用示例

2016-08-15 15:08 435 查看
datatables的用法:

Initialisation code

$(document).ready(function() {
$('#example').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "../examples_support/server_processing.php"
} );
} );

Server side (PHP) code

<?php
/*
* Script:    DataTables server-side script for PHP and MySQL
* Copyright: 2010 - Allan Jardine
* License:   GPL v2 or BSD (3-point)
*/

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Easy set variables
*/

/* Array of database columns which should be read and sent back to DataTables. Use a space where
* you want to insert a non-database field (for example a counter or static image)
*/
$aColumns = array( 'engine', 'browser', 'platform', 'version', 'grade' );

/* Indexed column (used for fast and accurate table cardinality) */
$sIndexColumn = "id";

/* DB table to use */
$sTable = "ajax";

/* Database connection information */
$gaSql['user']       = "";
$gaSql['password']   = "";
$gaSql['db']         = "";
$gaSql['server']     = "localhost";

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* If you just want to use the basic configuration for DataTables with PHP server-side, there is
* no need to edit below this line
*/

/*
* MySQL connection
*/
$gaSql['link'] =  mysql_pconnect( $gaSql['server'], $gaSql['user'], $gaSql['password']  ) or
die( 'Could not open connection to server' );

mysql_select_db( $gaSql['db'], $gaSql['link'] ) or
die( 'Could not select database '. $gaSql['db'] );

/*
* Paging
*/
$sLimit = "";
if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
{
$sLimit = "LIMIT ".mysql_real_escape_string( $_GET['iDisplayStart'] ).", ".
mysql_real_escape_string( $_GET['iDisplayLength'] );
}

/*
* Ordering
*/
if ( isset( $_GET['iSortCol_0'] ) )
{
$sOrder = "ORDER BY  ";
for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
{
if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
{
$sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
".mysql_real_escape_string( $_GET['sSortDir_'.$i] ) .", ";
}
}

$sOrder = substr_replace( $sOrder, "", -2 );
if ( $sOrder == "ORDER BY" )
{
$sOrder = "";
}
}

/*
* Filtering
* NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here, but concerned about efficiency
* on very large tables, and MySQL's regex functionality is very limited
*/
$sWhere = "";
if ( $_GET['sSearch'] != "" )
{
$sWhere = "WHERE (";
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
$sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string( $_GET['sSearch'] )."%' OR ";
}
$sWhere = substr_replace( $sWhere, "", -3 );
$sWhere .= ')';
}

/* Individual column filtering */
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
{
if ( $sWhere == "" )
{
$sWhere = "WHERE ";
}
else
{
$sWhere .= " AND ";
}
$sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string($_GET['sSearch_'.$i])."%' ";
}
}

/*
* SQL queries
* Get data to display
*/
$sQuery = "
SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns))."
FROM   $sTable
$sWhere
$sOrder
$sLimit
";
$rResult = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());

/* Data set length after filtering */
$sQuery = "
SELECT FOUND_ROWS()
";
$rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
$iFilteredTotal = $aResultFilterTotal[0];

/* Total data set length */
$sQuery = "
SELECT COUNT(".$sIndexColumn.")
FROM   $sTable
";
$rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
$aResultTotal = mysql_fetch_array($rResultTotal);
$iTotal = $aResultTotal[0];

/*
* Output
*/
$output = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $iTotal,
"iTotalDisplayRecords" => $iFilteredTotal,
"aaData" => array()
);

while ( $aRow = mysql_fetch_array( $rResult ) )
{
$row = array();
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if ( $aColumns[$i] == "version" )
{
/* Special output formatting for 'version' column */
$row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
}
else if ( $aColumns[$i] != ' ' )
{
/* General output */
$row[] = $aRow[ $aColumns[$i] ];
}
}
$output['aaData'][] = $row;
}

echo json_encode( $output );
?>

1、datatables分页显示

html代码:
<table class="table table-bordered table-striped table-hover table-heading beauty-table" id="usertable">

                         <thead>

                              <tr>

                                   <th>编号</th>

                                   <th>用户名</th>

                                   <th>状态</th>

                                   <th>头像</th>

                                   <th>邮箱</th>

                              </tr>

                         </thead>

                         <tbody>

                         <!-- Start: list_row -->                             

                         <!-- End: list_row -->

                         </tbody>

                         <tfoot>

                              <tr>

                                   <th>编号</th>

                                   <th>用户名</th>

                                   <th>状态</th>

                                   <th>头像</th>

                                   <th>邮箱</th>

                              </tr>

                         </tfoot>

                    </table>
<script type="text/javascript">

// Run Datables plugin and create 3 variants of settings

function AllTables(){

     userTable();

     LoadSelect2Script(MakeSelect2);

}

function MakeSelect2(){

     $('select').select2();

     $('.dataTables_filter').each(function(){

          $(this).find('label input[type=text]').attr('placeholder', 'Search');

     });

}

$("#usersubmit").click(function() {

     var artdata=$("#userform").serialize();

     $.ajax({

       type: 'POST',

       url: "{:U('Index/adduser')}",

       datatype:'text',

       data: artdata

     })

     .done(function( msg ) {

          alert( "Data Saved: " + msg );

     });

});

$('#myshow').click(function(){

     $('#myModal').modal({

        show:true,

        backdrop:'static',

     });

});

$(document).ready(function() {

    LoadFineUploader(FileUpload);

     // Add tooltip to form-controls

     $('.form-control').tooltip();

     LoadSelect2Script(DemoSelect2);

     // Load Datatables and run plugin on tables

     LoadDataTablesScripts(AllTables);

     // Load example of form validation

     LoadBootstrapValidatorScript(DemoFormValidator);

     WinMove();

});

</script>
js代码:
function userTable(){
     $('#usertable').dataTable({
          "aaSorting": [[ 0, "asc" ]],
          "processing":true,
//          "serverSide": true,
          "bServerSide": true,
     //     "paginate": true,
        "sAjaxSource": "Index/userlist",
          "sServerMethod": "POST",//特别注意该项设置。当在本地调试的时候没有设置此项,表格正常显示。当放在线上的时候分页数据可以显示,表格内容为空。查看发现aaData数据能从php中获取,但是前台页面就是不显示。最后加上此项才得以显示
          "sDom": "rt<'box-content'<'col-sm-6'i><'col-sm-6 text-right'p><'clearfix'>>",
          "sPaginationType": "bootstrap",
     //     "iDisplayLength": 5,
          "oLanguage": {
               "sSearch": "",
               "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
               "sInfoFiltered": "(筛选自 _MAX_ 条数据)",
               "sProcessing": "正在加载数据...",
               "sLengthMenu": '_MENU_',
               "oPaginate": {
               "sFirst":      "First",
               "sLast":       "Last",
               "sNext":       "下一页",
               "sPrevious":   "上一页"
             }
          },
          "aoColumns": [
            { "mData": 'id'},
            { "mData": 'name'},
            { "mData": 'status'},
            { "mData": 'avata'},
            { "mData": 'email'}
          ]
     });
}
php代码:
public function userlist(){

          header("Content-type: text/html; charset=utf-8");

          $sth = $this->dbh->query("select count(*) as counts from pos_user");//id name password status avata email  

          $count=$sth->fetch(PDO::FETCH_ASSOC);

          $iTotal = $count['counts'];

          $sLimit = "";

          if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )

          {

               $sLimit = "LIMIT ".mysql_real_escape_string( $_GET['iDisplayStart'] ).", ".

                    mysql_real_escape_string( $_GET['iDisplayLength'] );

          }

          if ( isset( $_GET['iSortCol_0'] ) )

          {

               $sOrder = "ORDER BY  ";

               for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )

               {

                    if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )

                    {

                         $sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."

                              ".mysql_real_escape_string( $_GET['sSortDir_'.$i] ) .", ";

                    }

               }              

               $sOrder = substr_replace( $sOrder, "", -2 );

               if ( $sOrder == "ORDER BY" )

               {

                    $sOrder = "";

               }

          }

    

          $stmt = $this->dbh->prepare("select SQL_CALC_FOUND_ROWS id,name,status,avata,email from pos_user $sLimit ");

          $stmt->execute();

          $data=$stmt->fetchAll(PDO::FETCH_ASSOC);

          $rResultFilterTotal=$this->dbh->prepare("SELECT FOUND_ROWS() as resultsrows");

          $rResultFilterTotal->execute();

          $aResultFilterTotal = $rResultFilterTotal->fetchAll(PDO::FETCH_ASSOC);

          $iFilteredTotal = $aResultFilterTotal[0]['resultsrows'];

         $aaData = array();

       foreach($data as $k=>$v){

          $aaData[$k]['id']=$v['id'];

          $aaData[$k]['name']=$v['name'];

          $aaData[$k]['status']=$v['status'];

          $aaData[$k]['avata']=$v['avata'];

          $aaData[$k]['email']=$v['email'];

       }

       $outputs=array();

       $outputs['sEcho']= intval($_GET['sEcho']);

       $outputs['iTotalRecords']=$iTotal;

       $outputs['iTotalDisplayRecords']=$iFilteredTotal;

       $outputs['aaData']=$aaData;

       echo(json_encode($outputs));         

     }
2、自定义列的内容,使用mRender

$('#usertable').dataTable({
          "aaSorting": [[ 0, "asc" ]],
          "processing":true,
//          "serverSide": true,
          "bServerSide": true,
     //     "paginate": true,
        "sAjaxSource": "Index/userlist",
          "sServerMethod": "POST",
          "sDom": "rt<'box-content'<'col-sm-6'i><'col-sm-6 text-right'p><'clearfix'>>",
          "sPaginationType": "bootstrap",
     //     "iDisplayLength": 5,
          "oLanguage": {
               "sSearch": "",
               "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
               "sInfoFiltered": "(筛选自 _MAX_ 条数据)",
               "sProcessing": "正在加载数据...",
               "sLengthMenu": '_MENU_',
               "oPaginate": {
               "sFirst":      "First",
               "sLast":       "Last",
               "sNext":       "下一页",
               "sPrevious":   "上一页"
             }
          },
          "aoColumns": [
            { "mData": 'id'},
            { "mData": 'name'},
            {
              "mData": 'status',
              "mRender": function ( data) {
                    if (data==1)
                    return '<font color="green">正常</font>';
                  else
                    return '<font color="red">禁用</font>';
            }
            },
            {
              "mData": 'avata',
              "mRender": function ( data) {//注意,mData不为空的时候,data代表了该属性的值,可以直接使用
                    return '<img class="img-rounded" src="/Uploads/'+data+'" alt="" width="75px" height="60px">';
            }
            },
            { "mData": 'email'},
            {
            "mData": null,//注意,当mData为空(null)的时候data参数代表的是整个数据对象,就可以使用data.id来获取属性
            "mRender": function ( data, type, full ) {
                    return '<a href="#"  onClick="alert('+data.id+'); return false">修改</a>  <a href="#"  onClick="alert('+data.id+'); return false">删除</a>';
            }
           }
          ]
     });


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php datatables