从json填充数据表头值

时间:2012-10-04 13:20:42

标签: jquery json datatable

我有如下所示的json

{
    "aaData": [

        [
         "Name",
         "Description",
         "Date"
        ],
        [
            {
                "displayValue": "Home Page",
                "link": "http://somelink.com"
            },
            "London",
            "1983"
        ],
        [
            {
                "displayValue": "Backlog",
                "link": "http://BacklogApp.com"
            },
            "Paris",
            "1999"
        ]
    ]
}

现在在js中,我使用sAjaxSource填充表,如下所示

$(document).ready(function() {
        $('#genericTable').dataTable( {
            "bProcessing": true,
            "sAjaxSource": "resources/json/" + key + ".json",
            "sPaginationType"   : "full_numbers",
            "bJQueryUI"         : true,
            "bRetrieve"         : true,
            "bPaginate"         : true,
            "bSort"             : true,
            "aaSorting"  : [[ 3, "desc" ]],
            "iDisplayLength"    : 50,
            "fnRowCallback": function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
                if(typeof aData[0] != 'string'){
                    $('td:eq(0)', nRow).html( '<a href="' + aData[0]['link'] +'" >'  +
                            aData[0]['displayValue'] + '</a>');
                }
            }
        }).columnFilter({ sPlaceHolder: "head:after",
            aoColumns: [ { type: "text" },
                         { type: "text" },
                         null
                       ]
        }); 
    });

我能够在jsp中使用硬编码标题名称填充表中的数据,但我也希望从json填充标题名称。 (名称,描述,日期)。我怎样才能做到这一点。

任何想法???

提前致谢!

1 个答案:

答案 0 :(得分:2)

可以在数据表初始化之前执行调用,以便您已经拥有列和数据。根据我的经验,您必须在“aoColumns”选项中定义列。

这是我的列标题的示例

"aoColumns" : [
                    { "sTitle" : "Status" },
                    { "sTitle" : "Name" },
                    { "sTitle" : "Url" },
                    { "sTitle" : "Page Views" },
                    { "sTitle" : "Leads" },
                    { "sTitle" : "Conv. Rate" },
                    { "sTitle" : "Actions" }
                ],

所以mb写这样的json,然后将其传递给ajax回调中的初始化

json = {
   "aoColumns": [ 
                   {"sTitle" : "Column Number 1"},
                   ....
                 ],
    "aaData": [ 
                 ....
                 .....
               ]
};

columns = json['aoColumns'];
data = json['aaData'];