Datatables: Uncaught TypeError: Cannot read property 'length' of undefined

前端 未结 1 1219
自闭症患者
自闭症患者 2021-01-01 05:07

I\'m attempting to use an ajax source with Datatables, and I\'ve run into some errors in doing. Previously Ajax was not being used with Datatables, and they were working fin

相关标签:
1条回答
  • 2021-01-01 05:50

    Your JSON output is wrong for the following reasons:

    1. The iTotalRecords and iTotalDisplayRecords fields are missing. This is why the pagination (and all the other functionalities) are broken (notice the message "Showing 1 to NaN of NaN entries (filtered from NaN total entries)" in the footer section). See this page for further details on server-side processing.
    2. There is some HTML code after the JSON response.

    Here is the extra HTML code (taken from test.php):

    <!-- Hosting24 Analytics Code -->
    <script src="http://stats.hosting24.com/count.php"></script>
    <!-- End Of Analytics Code -->
    

    In my opinion, the test.php script should be like the following:

    <?php 
    
    $link = mysqli_init();
    
    // Adjust hostname, username, password and database name before use!
    $db = mysqli_real_connect($link, "hostname", "username", "password", "database") or die(mysqli_connect_error());
    
    $SQL = 'SELECT `id`,`Minecraft_Username`,`Block_Name`,`Quantity`,`Cost`,`Trade_Status` FROM mctrade_trades';
    $result = mysqli_query($link, $SQL) or die(mysqli_error($link));
    
    $aaData = array();
    while ($row = mysqli_fetch_assoc($result)) {
        $aaData[] = $row;
    }
    
    $response = array(
      'aaData' => $aaData,
      'iTotalRecords' => count($aaData),
      'iTotalDisplayRecords' => count($aaData)
    );
    if (isset($_REQUEST['sEcho'])) {
      $response['sEcho'] = $_REQUEST['sEcho'];
    }
    
    header('Content-type: application/json'); 
    echo json_encode($response);
    
    ?>
    

    Be also aware that the mysql_* functions are deprecated, so you should use PDO or MySQLi instead; have a look at this answer for further details.

    0 讨论(0)
提交回复
热议问题