开发者

Populating a table from JSON with jQuery

开发者 https://www.devze.com 2023-04-11 05:40 出处:网络
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.

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: 'p开发者_C百科ublic.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.


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');
        });
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消