You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DataTables Ajax无法读取JSON数据,报Cannot read properties of undefined错误

解决DataTables读取JSON时的Uncaught TypeError错误

问题根源

你遇到的Uncaught TypeError: Cannot read properties of undefined (reading 'length')错误,是因为后端返回的是双重编码的JSON字符串——外层是带转义符的字符串,内部才是真正的JSON结构。DataTables解析后拿到的是字符串而非JSON对象,自然找不到配置中指定的data字段,进而触发读取length属性的错误。

解决方案

方案1:修复后端输出(推荐)

直接让后端输出原生JSON对象,不要将JSON序列化为字符串后再输出。正确的JSON格式应该是:

{"data":[{"ID": 415974, "userName": "johanna6060", "amount": 11, "userId": "johanna6060", "name": "johanna6060", "processId": "johanna6060", "trackingId": "companyname", "time": "johanna6060"}]}

去掉外层的引号和所有转义符,同时确保后端返回的Content-Type为application/json。

方案2:前端手动二次解析

如果后端暂时无法修改,可在DataTables的ajax配置中,通过dataSrc函数手动解析返回的字符串:

$('#papara-invest').DataTable({
    ajax: {
        url: "test.json",
        type: "GET",
        dataSrc: function(response) {
            // 将字符串格式的响应解析为JSON对象
            const parsedResponse = JSON.parse(response);
            // 返回DataTables需要的data数组
            return parsedResponse.data;
        }
    },
    colReorder: true,
    stateSave: true,
    dom: 'Bfrtip'
})

内容的提问来源于stack exchange,提问作者Sercan Aslan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 17:45:49