简体   繁体   中英

Read and create table from code not from .json file

I am trying to use this code that reads the json from a file. In my code I am creating the json from my database, as you can see below. How can I change the code to read the json from my code and not from the file? In here you can see how the json is being read, in my code you can see how the data is been read to create the table.

var columns = ["username", "user_id", "address", "state", "postal_code", "phone", "email"];

var level_classes = {
    "NEW": "new_client",
    "RENEWAL": "renewing_client",
    "CURRENT": "current_client"
};

$(document).ready(function() {
    $.getJSON("obtainUsers.php", function(data) {
        var $table = $('<table style="width: 100%;">');
        var $tbody = $('<tbody>');
        $table.append($tbody);
        var $tr = null;

        data.forEach(function(user, index) {
            if (index % 4 === 0) {
                $tr = $('<tr>');
                $tbody.append($tr);
            }
            $td = $('<td class="' + level_classes[user.level] + '">');
            columns.forEach(function(col) {
                $td.append(user[col]);
                $td.append($('<br>'));
            });
            $tr.append($td);
        });
        $('.runninglist').append($table);
    });
});

Thanks

You could do

$(document).ready(function() {
    $(".TableWithClass").each(function(){
        var ThisTableHere = $(this);
        $.getJSON($(this).data("url"), function(data) {
            var $table = ThisTableHere;
            .
            .
            Use your other data parameters here
            .
            .
            $('.runninglist').append($table);
    });
});

The only difference here is that you WILL have to wait for that page to execute before the client gets the full HTML, in the other one your page will load and do an ajax call

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