未捕获的类型错误:无法读取属性';长度';在尝试使用PHP填充响应数据表时未定义的


Uncaught TypeError: Cannot read property 'length' of undefined when trying to populate responsive datatable using PHP?

我正在尝试用对PHP脚本的AJAX请求填充响应数据表,响应以JSON_encode格式返回,我可以在XHR请求中看到响应:

["abc","def","ght","jkl"]

这是我正在使用的代码:

<table class="table table-striped table-bordered table-hover" id="dataTables-example">
  <thead>
    <tr>
      <th>Name</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <th>Name</th>
    </tr>
  </tfoot>
</table>
$('#dataTables-example').DataTable({
  responsive: true,
  "ajax": "search_autocomplete.php",
});

以下是PHP脚本:

if ($result->num_rows >0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    $list[] =$row['name'];
  }     
  echo json_encode( $list );            
}

当您想要插入数组数据源,即不是对象文字时,源必须是数组数组:

[["abc"],["def"],["ght"],["jkl"]]
$('#dataTables-example').DataTable({
  "ajax": {
    url: "search_autocomplete.php",
    dataSrc: ''
  }
});
if ($result->num_rows >0) {
  while($row = $result->fetch_assoc()) {
    $list[] = array($row['name']); //<----
  }     
  echo json_encode($list);            
}

如果您使用Jonathan的建议json_encode( array(data => $list)),情况也是如此——您仍然需要将每个项包装到一个数组中,否则您将获得adg等,因为dataTables按照其期望的数组访问每个字符串,每个字符都被视为一个数组项,即一列的数据。

if ($result->num_rows >0) {
  while($row = $result->fetch_assoc()) {
    $list[] = array($row['name']); //<----
  }     
  echo json_encode(array('data' => $list));
}
$('#dataTables-example').DataTable({
  "ajax": "search_autocomplete.php"
});

当只使用字符串值时,至少DataTables的ajax选项需要将响应封装在另一个对象中:

请注意,DataTables希望表数据是对象的data参数中的项数组。。。

{
    "data": [
        // row 1 data source,
        // row 2 data source,
        // etc
    ]
}

为了得到这个,你可以在编码之前将$list包装在另一个array()中:

echo json_encode( array( data => $list ) );

设置Json标头

header('Content-type: application/json');
echo json_encode( $list ); 

您还应该在while循环之前定义变量$list。如果未定义,则只返回姓氏。

$list = []