3

昨晚和今天我一直在敲我的头。我有一个 Laravel 4.2 项目,其中我的一些用户有更大的表(2000+)记录。我想使用 ajax 功能来动态提取数据。我使用了数据表中的 PHP 示例,但在 Firefox 检查器的“网络”选项卡中得到了一个没有响应的“”

这是我在页面上的 jquery:

jQuery(document).ready(function() {
    jQuery('#table_large').dataTable({

        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "/pets/records/data/",
            "type": "POST"
        }
    });
});

这是我的路线:

 Route::post('/pets/records/data/', 'PetsController@ajax');

这是我的存储库:

public function ajax(){



    $aColumns = array( 'custom_id', 'pet_name', 'pet_type', 'age', 'breed','gender','status','intake_date' );

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

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

    /* Database connection information */
    $gaSql['user']       = \Config::get('database.connections.mysql.username');
    $gaSql['password']   = \Config::get('database.connections.mysql.password');
    $gaSql['db']         = \Config::get('database.connections.mysql.database');
    $gaSql['server']     = \Config::get('database.connections.mysql.host');


    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     * 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' );die();
    }

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


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

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

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

    $sWhere = "";
    if ( isset($_POST['sSearch']) && $_POST['sSearch'] != "" )
    {
        $sWhere = "WHERE (";
        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        {
            if ( isset($_POST['bSearchable_'.$i]) && $_POST['bSearchable_'.$i] == "true" )
            {
                $sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string( $_POST['sSearch'] )."%' OR ";
            }
        }
        $sWhere = substr_replace( $sWhere, "", -3 );
        $sWhere .= ')';
    }

    /* Individual column filtering */
    for ( $i=0 ; $i<count($aColumns) ; $i++ )
    {
        if ( isset($_POST['bSearchable_'.$i]) && $_POST['bSearchable_'.$i] == "true" && $_POST['sSearch_'.$i] != '' )
        {
            if ( $sWhere == "" )
            {
                $sWhere = "WHERE ";
            }
            else
            {
                $sWhere .= " AND ";
            }
            $sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string($_POST['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() );
    //$rResultTotal = \DB::select(\DB::raw($sQuery));
    $aResultTotal = mysql_fetch_array($rResultTotal);
    $iTotal = $aResultTotal[0];

    /*
     * Output
     */

    if(isset($_POST['sEcho'])){
        $sEcho =  intval($_POST['sEcho']);
    }else{
        $sEcho = 0;
    }
    $output = array(
        "sEcho" => $sEcho,
        "iTotalRecords" => $iTotal,
        "iTotalDisplayRecords" => $iFilteredTotal,
        "aaData" => array()
    );

    try {
        while ($aRow = mysql_fetch_array($rResult)) {
            $row = array();
            for ($i = 0; $i < count($aColumns); $i++) {
                switch($aColumns[$i]){
                    case 'version':
                        /* Special output formatting for 'version' column */
                        $row[] = ($aRow[$aColumns[$i]] == "0") ? '-' : $aRow[$aColumns[$i]];
                        break;
                    default:
                        $row[] = $aRow[$aColumns[$i]];
                        break;
                }
            }

            $sanitized_row = [];
            foreach($row as $cell){
                $encoding = mb_detect_encoding($cell, mb_detect_order(), false);
                if($encoding == "UTF-8") {
                    $cell = mb_convert_encoding($cell, 'UTF-8', 'UTF-8');
                }
                $cell = iconv(mb_detect_encoding($cell, mb_detect_order(), false), "UTF-8//IGNORE", $cell);
                $sanitized_row[] = $cell;
            }

            $output['aaData'][] = $sanitized_row;
        }
    }catch (Exception $e){
        echo 'Error: ';
        var_dump($row);
    }
    $json =  json_encode( $output );
    if(json_last_error()) {
        print "json last error: ".json_last_error().'\n';
        print "json last error msg: ".json_last_error_msg().'\n';
    }

    return $json;

}

我遇到了编码错误,但我添加了一个 UT8 过滤,它不再抛出错误,但不确定它是否能解决问题。有没有人看到这段代码有什么明显的地方,或者有没有人对 Laravel 4.2 有更好的解决方案?谢谢,让我知道!

4

1 回答 1

0

从 DataTables 初始化代码和问题标签来看,datatables-1.10您正在使用 DataTables 1.10。但是,您的服务器端代码使用 DataTables 1.9 中使用的 POST 变量。DataTables 1.10 发送具有不同名称的变量(参见手册)。

此外,在 DataTables 1.10 发行版中,还有一个示例类 ( /examples/server_side/scripts/ssp.class.php),可简化服务器端处理(参见示例)。但是,此类不支持连接和子查询。对您来说应该没问题,因为您只使用一张表pets,请使用SSP::simple上面示例中所示的方法。

在 GitHub ( github.com/emran/ssp )上还有一个此类的增强版本,它应该支持连接和子查询。

于 2015-04-19T12:10:28.893 回答