zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    数据库设计_ERMaster安装使用_PowerDesigner数据设计工具
    Maven
    导入别的项目到我的eclipse上出现红色感叹号问题
    SSM集成
    SpringMVC (2)
    Maven: 把聚合工程下的项目导入 Ecplise
    SVN : 在SVN检测下来的Maven项目没有Maven标志
    SVN: 聚合工程下的子工程无法使用 svn:ignore
    Ecplise-SVN插件异常: 由于目标计算机积极拒绝,无法连接。
    Maven异常:Could not find artifact
  • 原文地址:https://www.cnblogs.com/i-blog/p/3641942.html
Copyright © 2011-2022 走看看