使用jQuery从JSON填充表 [英] Populating a table from JSON with jQuery

查看:104
本文介绍了使用jQuery从JSON填充表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是使用jQuery从JSON数据填充表的有效方法还是有更好/更低成本的方法?最大行数约为100.我不想使用插件。

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",
        ...
    },
    ...
}

编辑:基本上,我试图找出是否将所有行集中到字符串中,将其转换为jQuery对象然后将其附加到表中是一个好主意,假设这可以在页面上多次完成以刷新数据。

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.

推荐答案

而不是中的 语法和字符串构建,我会使用 jQuery.each()功能

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

喜欢这样:

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

这篇关于使用jQuery从JSON填充表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆