使用php通过JSON从MySQL数据库渲染DataTable

时间:2016-06-15 09:16:46

标签: javascript php mysql json datatable

我试图通过JSON在网页上呈现DataTable,php从MySQL数据库获取数据。但我无论如何都没有得到它...我打印出JSON文件(echo),但DataTable没有渲染,打开页面时出现错误:“.... DataTable #xxxxx - 无效的JSON响应......“但JSON是对的,我用很多JSON Validators进行了测试。我认为它没有格式化DataTable应该接受它的方式。

这是我的JSON格式,打印出来(回显),以测试我从服务器变成什么:

{  
   "aaData":[  
      [  
         "id12345",
         "bchange122",
         "textHEre",
         "https://url.here.com/images/ppp.png!",
         "hellooooo",
         "https://kbkbkbk.hello.com/subid=[usr.nr]-[b_tt]|[ba_ba]|[category]"
      ],
      [  
         "id23456",
         "test122",
         "test2HEre",
         "https://url.here.com/images/ppp.png!",
         "huhuhu",
         "https://kbkbkbk.hello.com/subid=[usr.nr]-[b_tt]|[ba_ba]|[category]"
      ],
      [  
         "id34567",
         "test233",
         "test344HEre",
         "https://url.here.com/images/ppp.png!",
         "ohlll",
         "https://kbkbkbk.hello.com/subid=[usr.nr]-[b_tt]|[ba_ba]|[category]"
      ],
      [  
         "id45678",
         "test344",
         "test4555Here",
         "https://url.here.com/images/ppp.png!",
         "eholl",
         "https://kbkbkbk.hello.com/subid=[usr.nr]-[b_tt]|[ba_ba]|[category]"
      ]
     ]
}

它是从这个php生成的:

<?php


                                        /* 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( 'pId', 'sName', 'lName', 'pLogUrl', 'incent', 'det_sUrl');

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

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

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


                                        /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
                                         * 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(

                                            "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;
                                        }

                                        $output = str_replace("\\/", "/", $output);

                                        echo json_encode($output, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);


                                    ?>

这里是从JSON渲染DataTable的Javascript代码:

$(document).ready(function() {
    $('#oShopPTable').DataTable( {
        "bProcessing": true,
        "bServerSide": true,
        "ajax": "AdminPage.php",
        "columns": [
            { "data": "pId" },
            { "data": "sName" },
            { "data": "lName" },
            { "data": "pLogUrl",
                render : function( data, type, full, meta ) {
                  return type == 'display' ? '<img src="'+ data + '"/>' : data
                }
            },
            { "data": "incent" },
            { "data": "detsUrl",
                render : function(data, type, full, meta) {
                    return type == 'display' ? '<a href="' + data + '">Go Shop</a>' : data
                }
            }
        ]
    } );
} );

这里是HTML:

<div class="panel-body">
                                            <table id="oShopPTable" class="display">
                                                <thead>
                                                    <tr>
                                                        <th>P ID</th>
                                                        <th>S Name</th>
                                                        <th>L Name</th>
                                                        <th>P Log URL</th>
                                                        <th>Incentiv</th>
                                                        <th>Det S URL</th>
                                                    </tr>
                                                </thead>
                                                <tfoot>
                                                    <tr>
                                                        <th>P ID</th>
                                                        <th>S Name</th>
                                                        <th>L Name</th>
                                                        <th>P Log URL</th>
                                                        <th>Incentiv</th>
                                                        <th>Det S URL</th>
                                                    </tr>
                                                </tfoot>
                                            </table>
                                        </div>

由于输出的回显来自页面,数据从数据库中获取,并转换为json,但不会呈现为DataTable: - / json的形式有效,但正如我所说,我认为不是DataTable需要的。如何在代码中将其转换为该表单?

这个javascript代码,从服务器上的JSON文件呈现DataTable(不从MySql-Server获取数据),工作正常。它是在同一页面上呈现的另一个DataTable:

$(document).ready(function() {
    $('#oShopMobTable').DataTable( {
        "ajax": "test.json",
        "columns": [
            { "data": "pId" },
            { "data": "sName" },
            { "data": "lName" },
            { "data": "pLogUrl",
                render : function( data, type, full, meta ) {
                  return type == 'display' ? '<img src="'+ data + '"/>' : data
                }
            },
            { "data": "incentiv" },
            { "data": "details.jToUrl",
                render : function(data, type, full, meta) {
                    return type == 'display' ? '<a href="' + data + '">Go Shop</a>' : data
                }
            }
        ]
    } );
} );

工作表是使用以下格式从以下test.json获取数据:

{
    "data": [
        {
            "sName": "hew",
            "lName": "hewii",
            "pId": "id21343123",
            "pLogUrl": "https://image.xxxx.com/yyy.png",
            "incentiv": "3p1",
            "details": {
                "tUrl": "https://url.here.com/",
                "desc": "textHere11",
                "juToSUrl": "http://surl.com/",
                "juToSBut": "shop"
            }
        },
        {
            "sName": "weh",
            "lName": "wehii",
            "pId": "id56569653",
            "pLogUrl": "https://image.xxxx.com/yyy.png",
            "incentiv": "3p221",
            "details": {
                "tUrl": "https://url.here.com/",
                "desc": "textHere11",
                "juToSUrl": "http://surl.com/",
                "juToSBut": "shop"
            }
        }
    ]
} 

并且html与上面完全相同(当然只是id不一样),对于从mysql获取数据的人(使用php)

1 个答案:

答案 0 :(得分:0)

我认为这个链接可以帮助你=): https://editor.datatables.net/examples/advanced/REST.html