jQuery DataTable配置后出现'Uncaught TypeError: 无法读取length属性'错误排查
jQuery DataTables 报错:Uncaught TypeError: Cannot read properties of undefined (reading 'length')
问题场景
表格结构:
<table id="NameList"> <thead> <tr> <th>ID</th> <th>Name</th> </tr> </thead> <tfoot> <tr> <th>ID</th> <th>Name</th> </tr> </tfoot> </table>
JS配置:
var table = $('#NameList').DataTable({ "ajax": '...php', "processing": true, "columns": [ {"data": "ID"}, {"data": "PeopleNames"} ], "order": [[0, 'desc']], "pageLength": 50 });
返回的JSON数据:
[ { "ID": "1", "PeopleNames": "Test1" }, { "ID": "2", "PeopleNames": "Test2" }, { "ID": "3", "PeopleNames": "Test3" }, { "ID": "4", "PeopleNames": "Test4" }, { "ID": "5", "PeopleNames": "Test5" }, { "ID": "6", "PeopleNames": "Test6" }, { "ID": "7", "PeopleNames": "Test7" }, { "ID": "8", "PeopleNames": "Test8" } ]
执行表格操作时抛出错误:Uncaught TypeError: Cannot read properties of undefined (reading 'length')
错误原因
DataTables 默认要求 AJAX 返回的 JSON 是包含data属性的对象(格式为{"data": [数组数据]}),它会读取该data数组的length属性来处理数据。但你返回的是纯数组,没有外层data字段包裹,导致DataTables找不到目标属性,进而抛出读取length失败的错误。
解决方案
有两种可行的解决方式:
方案1:修改PHP接口的JSON输出格式
让后端返回的数据外层包裹data字段,示例格式:
{ "data": [ {"ID": "1", "PeopleNames": "Test1"}, {"ID": "2", "PeopleNames": "Test2"}, {"ID": "3", "PeopleNames": "Test3"}, ... ] }
方案2:在DataTables配置中指定dataSrc参数
无需修改后端,直接在AJAX配置里声明使用返回的原始数组:
var table = $('#NameList').DataTable({ "ajax": { "url": '...php', "dataSrc": '' // 告诉DataTables直接使用返回的数组数据 }, "processing": true, "columns": [ {"data": "ID"}, {"data": "PeopleNames"} ], "order": [[0, 'desc']], "pageLength": 50 });
内容的提问来源于stack exchange,提问作者Arty
相关产品推荐
相关产品推荐

