【问题标题】:Creating columns dynamically with Datatables Jquery使用 Datatables Jquery 动态创建列
【发布时间】:2011-10-09 17:33:36
【问题描述】:

我正在使用带有 server_processing 的 Datatables 来获取数据,主要问题是我不想在 html (<th width="25" id ="th1">id</th>) 中指定列的名称,我想在通过 ajax 获取数据时动态创建列。

我的代码是:

$('#table').dataTable( {

    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": "server_processing.php?db="+pid+"&table="+id+"", //pid is the name of database and id the name of the table
     "bJQueryUI": true,
    "sPaginationType": "full_numbers"

} );             

【问题讨论】:

    标签: datatables


    【解决方案1】:

    “虽然 DataTables 可以直接从 DOM 获取有关表的信息,但您可能希望为 DataTables 提供每个单独列的特定说明。这可以使用 aoColumnDefs 参数或 aoColumns 以及给定的对象信息来完成每一列。”http://datatables.net/usage/columns

    类似:

    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
                })
            });
        }
    })
    

    data.php 在哪里

    {
        data:{
            total:200,
            count:3,
            list:[
                {foo:"Foo 1",bar:"Bar 1"},
                {foo:"Foo 2",bar:"Bar 2"},
                {foo:"Foo 3",bar:"Bar 3"},
            ]
        }
    }
    

    这里还有一个很好的设置总结: http://datatables.net/usage/options#aaData

    【讨论】:

    • 这是一个很好的答案,但它并没有回答实际的 OP。他在询问列名和列规范,而您正在回答数据。
    • 嘿乔瓦尼,感谢您的评论,但出于好奇,您是否错过了帖子的第一部分? aoColumns 描述列名。为了清楚起见,我添加了 JSON 数据。
    【解决方案2】:

    您可以在服务器端将 HTML 表格创建为字符串,然后在 ajax 调用中返回该字符串,如下所示。

        StringBuilder tblString = new StringBuilder();
    if (ds != null && ds.Tables != null && ds.Tables.Count > 0)
                        {
                            if (ds.Tables[0].Rows.Count > 0)
                            {
                                #region FormateTable
                                tblString.Clear();
    
                                tblString.Append("<table id='datatable1' class='table table-striped table-hover'>");
                                tblString.Append("<thead>" +
                                             "<tr> ");
                                foreach (var col in ds.Tables[0].Columns)
                                {
                                    tblString.Append("<th>" + col.ToString() + "</th>");
                                }
    
                                tblString.Append("</tr>" +
                                          " </thead><tbody>");
                                foreach (DataRow dr in ds.Tables[0].Rows)
                                {
                                    tblString.Append("<tr>");
    
                                    for (int colIndex = 0; colIndex < 
    ds.Tables[0].Columns.Count; colIndex++)
                                    {
                                        tblString.Append("<td>");
                                        tblString.Append(dr[colIndex] != null ? 
    dr[colIndex].ToString() : null);
                                        tblString.Append("</td>");
                                    }
                                    tblString.Append("</tr>");
                                }
    
                                tblString.Append("</tbody></table>");
    
                                #endregion
                            }
                        }
    Then return string builder like below:
    return Json(new
                {
                    message = msg,
                    List = tblString.ToString(),
                }, JsonRequestBehavior.AllowGet);
    

    现在在 AJAX 中使用:

     $.ajax({
                    url: '@Url.Action("GetData", "MyController")',
                    type: "POST",
                    data: addAntiForgeryToken({ Query: Query }),
                    dataType: 'JSON',
                    success: function (data) {
                        if (data.message == "Success") {
                        $('#itemtable').html(data.List);
                        return false;
                        }
                    },
                    error: function (xhr) {
                        $.notify({
                        message: 'Error',
                        status: 'danger',
                        pos: 'bottom-right'
                        });
                        }
                    });
                }
    

    HTML 代码:

     <div class="panel-body">
                    <div class="table-responsive" style="width:100%; height:564px; overflow-y:scroll;">
                        <div id="itemtable"></div>
                    </div>
                </div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-07
      • 2015-03-25
      • 2021-12-02
      相关资源
      最近更新 更多