使用Ajax和PHP进行简单的DataTable初始化

我在使用Ajax和PHP初始化DataTable时遇到了一些麻烦。 据检查员说,错误是:

Uncaught TypeError: Cannot read property 'length' of undefined jquery.dataTables.js:2649 (anonymous function) jquery.dataTables.js:2649 oSettings.jqXHR.$.ajax.success jquery.dataTables.js:8749 c jquery.js:3048 p.fireWith jquery.js:3160 k jquery.js:8235 r jquery.js:8778 

我按照数据表网站上的说明进行操作,但显然我做错了。 它不是php部分,我刚刚检查过它并且它返回了一个json文件。

这就是我所拥有的。

提前致谢。

     Chromo Insiders      @import 'DataTables/media/css/demo_table_jui.css';    

Chromo Insiders

email Last Name First Name Date Registered

这是脚本:

 $(document).ready(function(e) { $('#datatables').dataTable( { "bProcessing": true, "sAjaxSource": 'process.php' } ); }); 

万一你需要看看PHP代码:

 prepare($sql) or die ($sql); if(!$result->execute()) return false; if($result->rowCount() > 0) { $json = array(); while($row = $result->fetch()){ $json[] = array( 'email' => $row['email'], 'lastName' => $row['lastName'], 'firstName' => $row['firstName'], 'dateRegistered' => $row['dateRegistered'], 'state' => $row['state'] ); } $json['success'] = true; echo json_encode($json); } } catch(PDOException $e) { echo 'Error: ' . $e->getMessage(); } ?> 

您需要更改您的回复:

  if($result->rowCount() > 0) { $json = array(); while($row = $result->fetch()){ /** MAKE ARRAY NON ASSOCIATIVE **/ $json[] = array( $row['email'], $row['lastName'], $row['firstName'], $row['dateRegistered'], $row['state'] ); } /*** MAKE RESPONSE HAVE 'aaData' ENTRY ****/ $response = array(); $response['success'] = true; $response['aaData'] = $json; echo json_encode($response); 

参考这里: http : //datatables.net/release-datatables/examples/data_sources/ajax.html 。 特别:

DataTables期望一个带有数据源的数组“aaData”的对象。

你的表也没有“状态”列,尽管你的ajax响应确实……