DataTables新数据不起作用

时间:2013-04-08 11:55:21

标签: jquery-datatables

我的HTML文件中有一个表:

<!DOCTYPE html>
<head>
<link rel="stylesheet" href="../assets/data-tables/DT_bootstrap.css" />
<link rel="stylesheet" type="text/css" href="../assets/uniform/css/uniform.default.css" />
<link rel="shortcut icon" href="favicon.ico" />
</head>
<body class="fixed-top">
<table id="tabela_1">
<thead>
<tr>
<th>Contacto</th>
<th>Dt Receção</th>
<th>Dt Validade</th>
<th>Refª Cliente</th>
<th>Num Proposta</th>
<th>Estado</th>            
</tr>
</thead>
<tbody id="dados_tabela">
        <tr class="">
            <td>alex</td>
            <td>Alex Nilson</td>
            <td>1234</td>
            <td class="center">power user</td>
            <td><a class="edit" href="javascript:;">Edit</a></td>
            <td><a class="delete" href="javascript:;">Delete</a></td>
        </tr>
        <tr class="">
            <td>lisa</td>
            <td>Lisa Wong</td>
            <td>434</td>
            <td class="center">new user</td>
            <td><a class="edit" href="javascript:;">Edit</a></td>
            <td><a class="delete" href="javascript:;">Delete</a></td>
        </tr>
        <tr class="">
            <td>nick12</td>
            <td>Nick Roberts</td>
            <td>232</td>
            <td class="center">power user</td>
            <td><a class="edit" href="javascript:;">Edit</a></td>
            <td><a class="delete" href="javascript:;">Delete</a></td>
        </tr>
        <tr class="">
            <td>goldweb</td>
            <td>Sergio Jackson</td>
            <td>132</td>
            <td class="center">elite user</td>
            <td><a class="edit" href="javascript:;">Edit</a></td>
            <td><a class="delete" href="javascript:;">Delete</a></td>
        </tr>
        <tr class="">
            <td>webriver</td>
            <td>Antonio Sanches</td>
            <td>462</td>
            <td class="center">new user</td>
            <td><a class="edit" href="javascript:;">Edit</a></td>
            <td><a class="delete" href="javascript:;">Delete</a></td>
        </tr>
        <tr class="">
            <td>gist124</td>
            <td>Nick Roberts</td>
            <td>62</td>
            <td class="center">new user</td>
            <td><a class="edit" href="javascript:;">Edit</a></td>
            <td><a class="delete" href="javascript:;">Delete</a></td>
        </tr>

    </tbody>

</table>

<script src="../assets/js/jquery-1.8.3.min.js"></script>    
<script src="../assets/breakpoints/breakpoints.js"></script>    
<script src="../assets/bootstrap/js/bootstrap.min.js"></script>     
<script src="../assets/js/jquery.blockui.js"></script>
<script src="../assets/js/jquery.cookie.js"></script>
<script type="text/javascript" src="../assets/uniform/jquery.uniform.min.js"></script>
<script type="text/javascript" src="../assets/data-tables/jquery.dataTables.js">
</script>
<script type="text/javascript" src="../assets/data-tables/DT_bootstrap.js"></script>
<script src="../assets/js/app.js"></script>     

<script>
jQuery(document).ready(function() {         

var oTable = $('#tabela_1').dataTable({ 
"bServerSide": true,
"bRetrieve": true,
"oSearch": {"sSearch": "Initial search"},
"sAjaxSource": "x.php?id_cliente=1",
"aoColumns": [
{ "sTitle": "Nome"},
{ "sTitle": "Data"},
{ "sTitle": "d"},
{ "sTitle": "e"},
{ "sTitle": "e"},
{ "sTitle": "3"}
],
"iDisplayLength": 10,
"bRetrieve": true,
"bScrollCollapse": true
}); 
});

</script>
</body>
</html>

x.php文件发送以下数据:

(...)
$num=1;

echo '{"iTotalRecords":'.$totalRows_rs_listaconsultas.',
"iTotalDisplayRecords":"10",
"aaData":['; 


do {
if ($num>1){
echo ",";
}
echo '["',$row_rs_listaconsultas['nome'],'",
"',$row_rs_listaconsultas['datarecepcao'],'",
"',$row_rs_listaconsultas['validadeconsulta'],'",
"',$row_rs_listaconsultas['referenciaconsulta'],'",
"',$row_rs_listaconsultas['propostanumero'],'",
"',$row_rs_listaconsultas['estado'],'"]'; 
$num=$num+1;
} while ($row_rs_listaconsultas = mysql_fetch_assoc($rs_listaconsultas));

echo ']}';

该表显示了来自(“sAjaxSource”:“php / x.php?id_cliente = 1”)的数据。我可以看到所有数据,但排序列,搜索框和所有用于reating数据的命令都不起作用。似乎dataTable没有“看到”数据。我做错了什么? 谢谢你的帮助。 马里奥

1 个答案:

答案 0 :(得分:0)

这是你需要的。我在datatables网站上使用了代码:

html应该是这样的:

<html>
<head>
    </head>
    <body>
<table border="0" cellspacing="5" cellpadding="5" id="users" class="display">
    <thead><tr><th>id</th><th>name</th></tr></thead>
    <tbody><tr><td></td></tr></tbody>
</table>
<script src="http://code.jquery.com/jquery-latest.min.js"
        type="text/javascript"></script>
        <script src="jquery.dataTables.min.js"
                type="text/javascript"></script>
        <script type="text/javascript" charset="utf-8">
        $(document).ready(function() {
            $('#users').dataTable( {
                "bProcessing": true,
                "bServerSide": true,
                "sAjaxSource": "users.php"
            } );
        } );
        </script>
</body>
</html>

注意:我使用的表只包含两列id和name列。我的数据来自users.php文件。

users.php文件如下所示:

<?php
    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     * 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( 'id', 'name');

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

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

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

    /* REMOVE THIS LINE (it just includes my SQL connection user/pass) */
    //include( $_SERVER['DOCUMENT_ROOT']."/datatables/mysql.php" );


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

    /* 
     * Local functions
     */
    function fatal_error ( $sErrorMessage = '' )
    {
        header( $_SERVER['SERVER_PROTOCOL'] .' 500 Internal Server Error' );
        die( $sErrorMessage );
    }


    /* 
     * MySQL connection
     */
    if ( ! $gaSql['link'] = mysql_pconnect( $gaSql['server'], $gaSql['user'], $gaSql['password']  ) )
    {
        fatal_error( 'Could not open connection to server' );
    }

    if ( ! mysql_select_db( $gaSql['db'], $gaSql['link'] ) )
    {
        fatal_error( 'Could not select database ' );
    }


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


    /*
     * Ordering
     */
    $sOrder = "";
    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] ) ]."` ".
                    ($_GET['sSortDir_'.$i]==='asc' ? 'asc' : 'desc') .", ";
            }
        }

        $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 ( isset($_GET['sSearch']) && $_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 ( isset($_GET['bSearchable_'.$i]) && $_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 fatal_error( 'MySQL Error: ' . mysql_errno() );

    /* Data set length after filtering */
    $sQuery = "
        SELECT FOUND_ROWS()
    ";
    $rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or fatal_error( 'MySQL Error: ' . mysql_errno() );
    $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 fatal_error( 'MySQL Error: ' . mysql_errno() );
    $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. $aColumns = array( 'id', 'name'); //表格中的字段
  2. $sIndexColumn = "id"; //索引列
  3. $sTable = "users"; //表名
  4. 必要的连接变量:

    $ gaSql ['user'] =“”; $ gaSql ['password'] =“”; $ gaSql ['db'] =“”; $ gaSql ['server'] =“”;

  5. 这对我有用。