Jquery Datatables 动态列名

Datatables中文网:http://dt.thxopen.com/index.html

尝试:

<table id="sp_table" class="display">
  <tbody>
  </tbody>
</table>

//So you just make the Ajax call "manually" and then use the return to initialise DataTables.
$.ajax( {
    "url": 'whatever.php',
    "success": function ( json ) {
        json.bDestroy = true;
        $('#example').dataTable( json );
    },
    "dataType": "json"
} );



{
 
"aaData": [
[ "2010-07-27 10:43:08", "..."], [ "2010-06-28 17:54:33", "..."],
[ "2010-06-28 16:09:06", "..."], [ "2010-06-09 19:15:00", "..."]
] ,
 
"aaSorting": [
 [ 1, "desc" ]
],
 
"aoColumns": [
  { "sTitle": "Title1" },
  { "sTitle": "Title2" }
]
 
}
View Code

 

html

<table class="display" id="table"></table>
js

$("#table").dataTable({
    bJQueryUI:true,
    aoColumns:[
        {mDataProp:"foo",sTitle:"Foo Title"},
        {mDataProp:"bar",sTitle:"Bar Title"}
    ],
    fnServerData: function( sUrl, data, fnCallback){
        $.get('data.php', function(res) {
            fnCallback({  // process results to match table format
                "sEcho":config.sEcho,
                "iTotalRecords":res.data.total || res.data.count,
                "iTotalDisplayRecords":res.data.count || res.data.total,
                "aaData":res.data.list
            })
        });
    }
})
Where data.php is

{
    data:{
        total:200,
        count:3,
        list:[
            {foo:"Foo 1",bar:"Bar 1"},
            {foo:"Foo 2",bar:"Bar 2"},
            {foo:"Foo 3",bar:"Bar 3"},
        ]
    }
}
View Code
I add a new columns by recreating the whole datatable which is not recommended. But here's roughly how I do it:

1. Get column data via ajax

2. Push new column def:

aoColumnDefs.push({
"aTargets": [aoColumnDefs.length]
, "sTitle": sTitle
, "bSearchable": true
, "bVisible": true
, "bSortable": false
, "sClass": "recipe"
});

3. Push new row data into aaData:

$.each(aaData, function (i, rowData) {
rowData.push(newColData[rowData[1]] == undefined ? '' : newColData[rowData[1]]);
});

4. reinitialize DataTable

Removing a column:

1. Get the index into aaData and aoColumnDefs of the column to remove by the column index of the column to remove:

var dataIndex = myConstants.numFixedColumns + index;

2. Remove array element at the index obtained in #1.

$.each(aaData, function (i, data) {
data.splice(dataIndex, 1);
});

3. Resequence aTargets:

$.each(aoColumnDefs, function (i, column) {
column.aTargets = [i];
});

4. reinitialize DataTable
View Code
I've got DataTables working fine on my page- the only problem I have is dynamically declaring the table headers. I'm using an existing JSON object instead of using DataTables built in AJAX functions (for various reasons). Here's what I've tried so far...

Normal (works):
jQuery('#example').dataTable({
    "sPaginationType": "full_numbers",
    "aaData": results.DATA ,
    "aoColumns": [ {"sTitle": "Name"}, {"sTitle": "County"} ]
});

Give it the JSON (doesn't work):
jQuery('#example').dataTable({
    "sPaginationType": "full_numbers",
    "aaData": results.DATA ,
    "aoColumns": results.COLUMNS
});

Give it a string var (doesn't work):
jQuery.each(results.COLUMNS, function(i, value){
    column_names += '{"sTitle": "'+ value + '"}';
    if (i+1 != results.COLUMNS.length) column_names += ", ";
    }
);  // This creates the string '{"sTitle": "NAME"}, {"sTitle": "COUNTY"}' - confirmed in FireBug.
jQuery('#example').dataTable({
    "sPaginationType": "full_numbers",
    "aaData": results.DATA ,
    "aoColumns": [ column_names ]
});

Give it an object var (doesn't work):
function(results){
    var columns = new Array();
    jQuery.each(results.COLUMNS, function(i, value){
        columns.push(column_name={stitle: value})
    }
); //Creates the object, confirmed in FireBug
};
jQuery('#example').dataTable({
    "sPaginationType": "full_numbers",
    "aaData": results.DATA ,
    "aoColumns": [ columns ]
});

Help? 

PS: The code examples were just typed up- there may be some stray commas or something. All the code (and variables) were tested in the browser.
 fbasfbas August 2011
I can't see why approach #2 doesn't work unless your aoColumns are not defined correctly.
 luketheobscureluketheobscure August 2011
Interesting. Here's the truncated JSON data:

{"COLUMNS":["NAME","COUNTY"],"DATA":[[" John Doe","Fresno"],["Billy,"Fresno"],["Tom","Kern"],["King Smith","Kings"]]}

Resulting table renders correctly, just without the column names.
 fbasfbas August 2011
use the same format as aoColumns (an array of objects)

{"COLUMNS":[{ sTitle: "NAME"}, { sTitle: "COUNTY"}],"DATA":[[" John Doe","Fresno"],["Billy,"Fresno"],["Tom","Kern"],["King Smith","Kings"]]}

you can use any of the "init options - columns" values listed on http://www.datatables.net/ref or follow the examples at http://www.datatables.net/examples/
 luketheobscureluketheobscure August 2011
Thanks so much for helping me out.

In the end, I added this right before I declared my dataTable:

var columns = [];
jQuery.each(results.COLUMNS, function(i, value){
    var obj = { sTitle: value };
     columns.push(obj);
});

In case anyone else is looking, this takes the native way that ColdFusion returns JSON columns and puts it into what dataTables expects.
View Code

 

转载于:https://www.cnblogs.com/i-blog/p/3641942.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值