使用Datatables Jquery动态创建列

9
我正在使用Datatables结合server_processing获取数据,主要问题是我不想在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"

} );             
2个回答

5
“虽然DataTables可以直接从DOM中获取关于表格的信息,但您可能希望为每个单独的列提供特定的指令。这可以使用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
            })
        });
    }
})

数据.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。他在问列名和列规范,而你正在回答数据相关的内容。 - SkyWalker
嘿,Giovanni,感谢你的评论,但是出于好奇,你错过了帖子的第一部分吗?aoColumns描述了列名。我添加JSON数据以清晰明了。 - Shanimal

0

您可以在服务器端创建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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接