无效的JSON格式数据表

时间:2018-12-13 05:26:46

标签: javascript html css json datatable

我正在尝试实现服务器端数据表,但是会引发Invalid JSON format错误。

CDN

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">

HTML

<table id="example" class="display" style="width:100%">
    <thead>
        <tr>
            <th>EmployeeCode</th>
            <th>EmployeeName</th>
            <th>ManagerName</th>
            <th>DesignationName</th>
        </tr>
    </thead>
</table>

JS

<script>
$(document).ready(function() {
    $('#example').DataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": "/api/url",
        "columns": [
            { data: "EmployeeCode" },
            { data: "EmployeeName" },
            { data: "ManagerName" },
            { data: "DesignationName" }
        ],
    } );
} );
</script>

JSON

{
  "Results":[{"EmployeeCode": "12345"}], // This is just a sample of data
  "CurrentPage": 1,
  "PageCount": 42,
  "PageSize": 10,
  "RecordCount": 417
}

2 个答案:

答案 0 :(得分:0)

通过查看XHR / Ajax调用返回给服务器的JSON,很清楚问题出在哪里。它应该只包含如下所示的预期数据:

[
  {'EmployeeCode':12345,EmployeeName:'abcde',...},
  {'EmployeeCode':12346,EmployeeName:'fghij',...},
  ...
]

相反,您的JSON包含其他属性,并且数据嵌套在“结果”属性下。同时查看documentation,我认为您需要格式化JSON以包含数据属性:

{
  "draw": 1,
  "recordsTotal": 57,
  "recordsFiltered": 57,
  "data": [
    [
      "12345",
      "John Smith",
      "Adam James",
      "Manager",
    ],
    ...
}

因此,作为简单修复,使用Ankush在数据表配置中建议的'dataSrc':'Results'属性。

答案 1 :(得分:0)

使用Ubuntu 18.10属性使datatable知道从何处收集数据:

dataSrc

有关$(document).ready(function() { $('#example').DataTable( { "processing": true, "serverSide": true, "ajax": "/api/url", "dataSrc": function (json) { debugger; return json.data; }, "columns": [ { data: "EmployeeCode" }, { data: "EmployeeName" }, { data: "ManagerName" }, { data: "DesignationName" } ], } ); } ); 的更多详细信息,请参见here