【问题标题】:Show JSON Data in Jquery Datatables在 Jquery 数据表中显示 JSON 数据
【发布时间】:2017-10-02 15:51:19
【问题描述】:

我一直在尝试在 jQuery DataTables 组件中获取我的 JSON 数据。

首先我编写了 JavaScript 代码以及如下代码所示的视图:

$(document).ready(function () {
    $('#myData').DataTable({
        lengthChange: false,
        ajax: {
            url: "http://amp-local/api/wipbin/FetchChild/",
            // dataSrc: 'allk'
        },
        columns: [
            { data: "name" },
            { data: "numbers" }
        ],
        select: true
    });
});

我的看法:

<table id="myData" class="table table-striped table-bordered" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Numbers</th>
        </tr>
    </thead>
</table>

我的 JSON:

[{
    "numbers": "38",
    "name": "Bllaca"
}, {
    "numbers": "28",
    "name": "Kaess"
}, {
    "numbers": "27",
    "name": "droessmer"
}, {
    "numbers": "24",
    "name": "friedricha"
}]

结果是这个错误:

TypeError: undefined is not an object (evaluating 'f.length')

我的桌子是空的。

【问题讨论】:

  • 您的 JSON 无效。
  • 应该怎么样?
  • 你最后错过了}]
  • 啊,因为我只显示了我的 json 的一部分
  • 好吧,无论如何添加}]... 可以限制它,但它至少在您的示例中必须是有效的。

标签: javascript json datatable


【解决方案1】:

当对 AJAX 请求使用服务器端处理时,它期望 JSON 数据以 DataTables 所需的special format 形式返回。 JSON响应对象的以下字段是必需的:drawdatarecordsTotalrecordsFiltered。您需要使您的服务器响应符合expected format
例如,您的第一反应应该如下:

{
  "draw": 1,
  "recordsTotal": 4,
  "recordsFiltered": 4,
  "data": [
    {
      "numbers": "38",
      "name": "Bllaca"
    }, {
      "numbers": "28",
      "name": "Kaess"
    }, {
      "numbers": "27",
      "name": "droessmer"
    }, {
      "numbers": "24",
      "name": "friedricha"
    }
  ]
}

【讨论】:

  • 我怎样才能改变这个?直接查询?
  • @Sofiane,这是对 server 响应的要求。您需要在服务器端进行更改。
猜你喜欢
  • 1970-01-01
  • 2018-05-09
  • 2015-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
  • 1970-01-01
相关资源
最近更新 更多