自定义JSON以填充数据表

时间:2018-09-11 17:34:10

标签: java jquery json datatable

我是根据Ajax json创建数据表的。

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。有任何想法吗?

1 个答案:

答案 0 :(得分: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' }
   ]
})

如果ypu指定了<thead>部分,则可以跳过title