javascript - 使用 php 通过 JSON 渲染 MySQL 数据库中的 DataTable

标签 javascript php mysql json datatable

我正在尝试通过 JSON 在网页上呈现 DataTable,并使用 php 从 MySQL 数据库获取数据。但我无论如何都没有得到它..我得到了 JSON 文件打印出来(回显),但 DataTable 没有呈现,打开页面时我收到错误:“....DataTable #xxxxx - 无效的 JSON 响应...”但是 JSON 是正确的,我用许多 JSON 验证器对其进行了测试。我认为它只是没有按照数据表应该接受的方式格式化。

这是我的 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 呈现数据表的 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"
            }
        }
    ]
} 

对于从mysql获取数据(用php)的html来说,和上面一模一样(当然只是id不一样)

最佳答案

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

关于javascript - 使用 php 通过 JSON 渲染 MySQL 数据库中的 DataTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37831154/

相关文章:

javascript - 如何使用以编程方式更改的 Ember.TextBox 数据来更新存储?

php - 如何在 PHP 中使用模数根据两种不同的模式将 CSS 类添加到图像网格中?

php - 我的数据库模型(很糟糕)让人头疼,如何改进它?

javascript - 在 e2e 测试中测试路由 Karma 时出错

javascript - 为什么这不起作用? javascript

php - 在条件 (if) 语句中使用 CodeCeption 断言

java - 无法删除、更改、更改...列名称 'number of shares' 带空格

PHP PDO-MYSQL : How to use database connection across different classes

java - JPA 返回对象引发内部服务器错误

javascript - 在数组项之间进行操作