简体   繁体   中英

JSON array Tabulator js table

I have a Tabulator datatable in my HTML file. 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 .

This is how my JS file looks like:

$(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:

{"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.

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:

//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:

$(".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('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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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