开发者

Creating columns dynamically with Datatables Jquery

开发者 https://www.devze.com 2023-04-11 15:09 出处:网络
I am using Datatables with server_processing to get data, the main issue is i dont want to specify the name of the columns in html (<th width=\"25\"id =\"th1\">id</th>), I want to create c

I am using Datatables with server_processing to get data, the main issue is i dont want to specify the name of the columns in html (<th width="25" id ="th1">id</th>), I want to create columns dynamically when getting data by ajax.

My code is :

$('#table').dataTable( {

    "bProcessing": true,
    "bServerSide": true,
    "sAjaxSource": "server_processing.php?db="+pid+"&table="+id+"", //pid is the name of da开发者_开发百科tabase and id the name of the table
     "bJQueryUI": true,
    "sPaginationType": "full_numbers"

} );             


"Although DataTables can obtain information about the table directly from the DOM, you may wish to give DataTables specific instructions for each individual column. This can be done using either the aoColumnDefs parameter, or aoColumns and the object information given for each column." — http://datatables.net/usage/columns

Something like:

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"},
        ]
    }
}

There's also a good summary of setting this up here: http://datatables.net/usage/options#aaData


You can create HTML table as string at server side then return the string in ajax call like below.

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

Now use in 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 code:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号