【问题标题】:Custom JSON to populate a Datatable自定义 JSON 以填充数据表
【发布时间】:2019-02-16 06:40:57
【问题描述】:

我正在从 Ajax json 创建一个 DataTable。

resultTable = $('#changeTable').DataTable({
            "order": [[0, "desc"]],
            "pageLength": 50,
            "scrollX": true,
            "lengthMenu":[[50,100,250, -1], [50, 100, 250, "All"]],
            "dom":'<"toolbar">ltipr', //write ltfipr to show a search bar
            "ajax":{
                url:"api/changes",
                "dataType":"json",
                timeout:15000
            }
    });

DataTables 创建但显示错误:

DataTables 警告:表 id=changeTable - 请求的未知参数 '0' 表示第 0 行第 0 列。有关此错误的更多信息,请 见http://datatables.net/tn/4

我的 JSON 如下所示

{"data":
    [
       {"id":1,
        "createdDate":"Apr 18, 2018 4:10:58 PM",
        "source":"manual upload",
        "emailId":"manual upload",
        "attachmentId":"manual upload",
        ...,},
       {next objet}]}

这样的 JSON 对象是在我的 Java 控制器中创建的:

@RequestMapping(value = "/api/changes", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public String getChanges(){
        Optional<List<PriceChange>> priceChangeList = pcService.findAllPriceChanges();
        JsonObject result = new JsonObject();
        if (priceChangeList.isPresent()) {
            result.add("data", new Gson().toJsonTree(priceChangeList.get()));
            return  result.toString();
        }
        return null;

    }

我不知道如何将此信息与dataSrc 属性一起使用以使其适用于DataTable。有什么想法吗?

【问题讨论】:

  • 什么是pcService?它返回什么?请提供有关dataSrc 的更多背景信息。
  • 您是否尝试过使用 Jackson 而不是 GSON 进行反序列化?
  • 你有 result = new JsonObject(); 但看起来你的 "{ data": [] 是一个 JsonArray。

标签: java jquery json datatable


【解决方案1】:

您只需要为表格定义columns。如果你有

<table id="changeTable"></table>

将此添加到您的 DataTables 选项中:

resultTable = $('#changeTable').DataTable({
  ...,
  columns: [
     { data: 'id', title: 'id' },
     { data: 'createdDate', title: 'createdDate' },
     { data: 'source', title: 'source' },
     { data: 'emailId', title: 'emailId' },
     { data: 'attachmentId', title: 'attachmentId' }
   ]
})

如果您指定了&lt;thead&gt; 部分,您可以跳过title 部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 2020-05-31
    • 2022-11-11
    • 2018-02-06
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多