返回json对象时使用datatables

返回json对象时使用datatables,json,ajax,datatables,Json,Ajax,Datatables,我想使用datatable从txt或一些web api返回JSON。 因此,如果数据采用以下格式(coopInformation.txt),则一切工作正常: 这是我的jquery调用: $(document).ready(function() { $('#example').DataTable({ ajax: 'ajax/data/coopInformation.txt', columns: [ {

我想使用datatable从txt或一些web api返回JSON。 因此,如果数据采用以下格式(coopInformation.txt),则一切工作正常:

这是我的jquery调用:

$(document).ready(function() {
    $('#example').DataTable({
        ajax: 'ajax/data/coopInformation.txt',
        
        columns: [
            {
                data: 'employer'
            },
            {
                data: 'degree'
            },           
            {
                data: "city"
            },
            {
                data: "term"
            }
        ]
    });
});
但当json对象不以“data”开头时,例如以“coopInformation”开头时,即使我将列更改为coopInformation,该调用也会返回一个错误:

$(document).ready(function() {
    $('#example').DataTable({
        ajax: 'ajax/data/coopInformation.txt',
        
        columns: [
            {
                coopInformation: 'employer'
            },
            {
                coopInformation: 'degree'
            },           
            {
                coopInformation: "city"
            },
            {
                coopInformation: "term"
            }
        ]
    });
});
未捕获的TypeError:无法读取未定义的属性“length” 在jquery.dataTables.min.js:65 在h(jquery.dataTables.min.js:51) 在Object.success(jquery.dataTables.min.js:52) 着火时(jquery-3.5.1.js:3496) 在Object.fireWith[as resolveWith](jquery-3.5.1.js:3626) 完成时(jquery-3.5.1.js:9786) 在XMLHttpRequest。(jquery-3.5.1.js:10047)

看起来这个LIB是预先定义好使用“数据”的,否则我错了。。。 我的问题是:如何使用其他东西而不是“数据”来拨打这样一个简单的电话。在datatables web上,所有示例都与此“数据”一起使用

亲切问候,,
Milan

默认情况下,DataTables希望您的JSON数组命名为
“data”
——就像您的第一个JSON示例:
{“data”:[…]}
。如果JSON具有不同的结构,则需要使用
dataSrc
选项告知DataTables数组在JSON中的位置。例如,如果数组没有名称(您的第二个示例),则使用
dataSrc:“
”。有关更多详细信息和示例,请参阅。请注意,您确实需要在列定义中使用
数据:“雇主”
,而不管您的JSON的结构如何-而不是像
coopInformation:“雇主”
,它将永远无效。这里的
数据
是一个关键字,如
标题
名称
等。这些都是DataTables预定义的,用于表示不同类型的列相关信息。
$(document).ready(function() {
    $('#example').DataTable({
        ajax: 'ajax/data/coopInformation.txt',
        
        columns: [
            {
                coopInformation: 'employer'
            },
            {
                coopInformation: 'degree'
            },           
            {
                coopInformation: "city"
            },
            {
                coopInformation: "term"
            }
        ]
    });
});