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
  • 相关阅读:
    [LeetCode] 278. First Bad Version 第一个坏版本
    [LeetCode] 119. Pascal's Triangle II 杨辉三角 II
    [LeetCode] 118. Pascal's Triangle 杨辉三角
    [LeetCode] 272. Closest Binary Search Tree Value II 最近的二叉搜索树的值 II
    校验数组中是否存在某一个元素
    css sprites 图片位置计算
    后台获取当前客户端浏览器的类型
    Linq,拉姆达表达式注意!
    window.open 设置高和宽无效
    asp:FileUpload 控件上传多文件
  • 原文地址:https://www.cnblogs.com/i-blog/p/3641942.html
Copyright © 2011-2022 走看看