Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating a table from JSON with jQuery

Is this an effective way to populate a table from with JSON data using jQuery or is there a better/less costly way? The maximum number of rows will be around 100. I'd prefer not to use a plugin.

JS:

$.ajax({
    url: 'public.json',
    dataType: 'json',
    success: function(data) {
        var row = '<tr class="header">';
        for (var i in data.headers) {
            row += '<th style=""><a href="#" class="sort"><span>' + data.headers[i] + '</span></a></th>';
        }
        row += '</tr>'
        $(row).appendTo('table.data');
        row = '';
        for (var i in data.rows) {
            row += '<tr id="' + i + '">';
            row += '<td>' + data.rows[i].date + '</td>';
            row += '<td>' + data.rows[i].company + '</td>';
            row += '<td>' + data.rows[i].location + '</td>';
            ...
            row += '</tr>';
        }
        $(row).appendTo('table.data');
    },
});

JSON:

{
    "headers": {
        "date": "Date",
        "company": "Company",
        "location": "Location",
        ...
    },
    "rows": [{
        "date": "09/18/2011",
        "company": "Company name",
        "location": "US",
        ...
    },
    ...
}

EDIT: Essentially, I'm trying to figure out if lumping all the rows into a string, turning it into a jQuery object and then appending it to the table is a good idea, assuming this can be done multiple times on the page to refresh the data.

like image 269
Alex Avatar asked Oct 05 '11 22:10

Alex


1 Answers

Rather than the for .. in syntax and the string-building, I would use the jQuery.each() function

Like this:

$.ajax({
    url: 'public.json',
    dataType: 'json',
    success: function(data) {
        var $tr =$('<tr>').addClass('header');
        $.each(data.headers, function(i,header){
            $tr.append($('<th>').append($('a').addClass('sort').attr('href','#').append($('span').text(header))));
        });
        $tr.appendTo('table.data');
        $.each(data.rows,function(i,row){
            $('<tr>').attr('id',i).
                append($('<td>').text(row.date)).
                append($('<td>').text(row.company)).
                append($('<td>').text(row.location)).appendTo('table.data');
        });
    }
});
like image 80
Hari Pachuveetil Avatar answered Nov 04 '22 11:11

Hari Pachuveetil