DataTables - 未捕获的类型错误:无法读取未定义属性'length'

5

我看到了很多这个问题的例子,但仍然找不到解决方法。

错误显示在以下代码中的jquery.dataTables.js(版本1.10.4)的第3287行:

// Got the data - add it to the table
    for ( i=0 ; i<aData.length ; i++ ) {
        _fnAddData( settings, aData[i] );
    }

这是我的控制器。由于现在缺少数据库连接,所以控制器是这样的,但最终会以与$data相同的格式返回JSON。我尝试了几种解决错误的方法,但不断遇到其他问题。JSON是有效的。
public function test()
{
  $data = '{"persons": [{"branch": "CORP","phone_numbers": [{"desk": "5223422117"},{"mobile": "5022319224"},{"branch": "422-922-2291"}],"email": "twilliams@test.com","preferred_name": "Thomas","person_id": 368,"department": "IT","first_name": "Thomas","title": "Programming Manager","last_name": "Williams"}]}';

  $data = json_encode($data);
  echo $data;

}

我的JavaScript

$(document).ready(function() {
     $('#directory_table').dataTable( {
         "ajax": {
             "url": "test",
             "type": "JSON"
         },
         "aoColumns": [
             { "persons": "preferred_name" },
             { "persons": "last_name" },
             { "persons": "phone_numbers.0" },
             { "persons": "phone_numbers.1" },
             { "persons": "phone_numbers.2" },
             { "persons": "email" },
             { "persons": "department" },
             { "persons": "title" }
         ]
     } );
 } );

我的HTML

<table id='directory_table' class="display">
    <thead>
        <tr style='background: #186A9F; color: white;'>
            <th>First Name </th>
            <th>Last Name</th>
            <th>Desk Number</th>
            <th>Mobile</th>
            <th>Branch</th>
            <th>Email</th>
            <th>Department</th>
            <th>Title</th>
        </tr>
    <thead>
</table>
1个回答

9

原因

默认情况下,DataTables 期望 JSON 响应具有特定的结构,请参见文档

由数组组成的数组:

{
    "data": [
        [ "value1", "value2" ],
        ...
    ]
}

对象数组:

{
    "data": [
        {
           "attr1": "value1",
           "attr2": "value2"
        },
        ...
    ]
}

错误是由于响应中保存对象数组的数据属性名(persons)与默认值(data)不同导致的。

解决方案

使用ajax.dataSrc选项来定义要读取的数据源对象(即Ajax请求返回的对象)中的属性。

$('#directory_table').dataTable( {
   "ajax": {
      "url": "test",
      "dataSrc": "persons"
   },
   "columns": [
      { "data": "preferred_name" },
      { "data": "last_name" },
      { "data": "phone_numbers.0.desk" },
      { "data": "phone_numbers.1.mobile" },
      { "data": "phone_numbers.2.branch" },
      { "data": "email" },
      { "data": "department" },
      { "data": "title" }
   ]
});

如果您可以将JSON响应中的数据属性名称从persons更改为data,那么就不需要添加"dataSrc": "persons"

演示

请查看此jsFiddle以获取代码和演示。

链接

有关此错误和其他常见控制台错误的更多信息,请参见jQuery DataTables: Common JavaScript console errors


是的,URL 在我的端上是正确的。我能够运行 Ajax,访问我的控制器,并且我的 JSON 通过 DataTables JavaScript 传递。我会尽快尝试这个方法。感谢您的反馈。 - Philip Wiggins

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接