简体   繁体   English

JSON数组制表器js表

[英]JSON array Tabulator js table

I have a Tabulator datatable in my HTML file. 我的HTML文件中有一个Tabulator数据表。 Looks like this: 看起来像这样:

<div class="example-table">/div>

I have a JavaScript file that would populate my table with data by calling a rest API that returns with a JSON . 我有一个JavaScript文件,该文件将通过调用返回JSON的rest API来用数据填充表。

This is how my JS file looks like: 这是我的JS文件的样子:

$(document).ready(function() {

    $(".example-table").tabulator({
        columns : [ {
            title : "ID",
            field : "myjson.firstname",
            width : 250
        }, {
            title : "Pred",
            field : "myjson.pred",
            sorter : "number",
            align : "left",
            formatter : "progress",
            width : 200
        }, ],
    });

    var tabledata = [];

    $.getJSON('http://127.0.0.1:7001/MySerices/service/rest', function(json) {
        tabledata.append(json);
    });

    $(".example-table").tabulator("setData", tabledata);

});

And the JSON which the REST service returns with looks like this: REST服务返回的JSON如下所示:

{"myjson":
[{"firstname":"Piter","pred":"0,616540492"},
{"firstname":"Piter","pred":"0,616540492"}
]}

The Tabulator table apears but without any data. 制表器表将显示,但没有任何数据。 If I check my JS log, I can see the request is done wihout any error, and i can see the JSON in my response. 如果检查我的JS日志,则可以看到请求完成而没有任何错误,并且可以在响应中看到JSON。

Can you help me how can I do it? 您能帮我怎么做?

Thank you! 谢谢!

There are three major errors in your code. 您的代码中存在三个主要错误。

First , your JSON response, the response should be as the tabulator js documentation shows: 首先 ,您的JSON响应,该响应应如制表js 文档所示:

//An array of objects not wrapped in an object
[
   {"firstname":"Piter","pred":"0,616540492"},
   {"firstname":"Parker","pred":"0,42325456"}
]

Second , the columns field should match each row: 其次 ,columns字段应与每一行匹配:

$(".example-table").tabulator({
    columns : [ {
        title : "ID",
        field : "firstname",//changed here
        width : 250
    }, {
        title : "Pred",
        field : "pred",//and here
        sorter : "number",
        align : "left",
        formatter : "progress",
        width : 200
    }, ],
});

Third , getJSON is asynchronous, so you need to get and set the data only when the response arrives: 第三getJSON是异步的,因此仅在response到达时才需要获取和设置数据:

$.getJSON('http://127.0.0.1:7001/MySerices/service/rest', function(response) {
    //response is already a parsed JSON
    $(".example-table").tabulator("setData", response);

});

PS: arrays don't have the append method, you can use unshift or push to prepend or append data to the array . PS:数组没有append方法,您可以使用unshiftpush将数据前置或追加到array

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM