Jquery DataTables 用法分享

来源:互联网 发布:交换机端口流量监控 编辑:程序博客网 时间:2024/06/07 09:45
        由于项目需要,用到了Jquery DataTables 表格插件,感觉jquery  Datatables 这个插件还是挺好用的,功能全面,设置灵活。分页,列拖动,排序这些都有,结合Bootstrap 样式还是挺高大上的,各种示例可以参照
http://datatables.club/ 虽说如此,但我感觉相关资料还是比较少,大多还是英文,对于.NET 开发的Demo 更是不容易找到,因为自己在项目中用到,还花了不少时间和精力,也走了许多弯路,现在想把一些总结和感
悟在这里和大家分享分享。
先给大家贴一些效果图片吧!
 



 
Jquery DataTables 所需要的js库文件包括:
<script src="~/Content/jquery/jquery-2.1.4.min.js"></script>  // jquery 库
<script src="~/Content/jquery/jquery.dataTables.min.js"></script> //dataTables 库
<script src="~/Content/datatables/dataTables.bootstrap.min.js"></script> //dataTables  结合bootstrap 样式相关的补充
<script src="~/Content/datatables/dataTables.select.min.js"></script> //datatables 选中行相关的库
<script src="~/Content/jquery/jquery.resizableColumns.min.js"></script> //实现datatables 列拖动大小的JS


样式表包括:
<link href="~/Content/datatables/dataTables.bootstrap.min.css" rel="stylesheet" /> //datatables 基础样式
<link href="~/Content/datatables/dataTables.select.min.css" rel="stylesheet" /> //datatables 选中行样式
<link href="~/Content/jquery/jquery.resizableColumns.css" rel="stylesheet" /> 列拖动大小时相关的样式


Html 页面内容


<div class="dataTable_wrapper datatables-container">
    <table class="table dataTable table-striped table-bordered table-hover" id="dataTables-AccountList">
        <thead>
            <tr>
                <th width="60">
                    <div class='checkbox'>
                        <label>
                            <input type="checkbox" id="chk_all" class="checkbox" />
                        </label>
                    </div>
                </th>
                <th width="60">年月</th>
                <th width="360">描述</th>
                <th width="100">分类</th>
                <th width="60">帐目金额</th>
                <th width="100">类型</th>
                <th width="60">计帐日期</th>
                <th width="60">计帐人</th>
                <th width="100">计录时间</th>
            </tr>
        </thead>
        <tbody>
<!--
   --这里可以是表格的内容 <tr><td></td>...</tr>... 因为Datatables 生成表格有两种方式:
   -- 一是根据HTML 内容直接生成可分页表格,
   -- 二是通过Ajax 调用后台服务端 返回Json 最终生成可分页的表格
   -- 下面主要分享的是如果通过服务端返回数据生成表格
-->
        </tbody>
    </table>
</div>


为了实现当列宽太小,而内容太多影响显示效果可以加入如下样式:
.dataTable
{
    width: 100%;
    min-width: 540px;
    table-layout: fixed;
}


    .dataTable td, .dataTable th
    {
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
    }


JS 代码如下:
//定义一下全局变量,将DataTable 赋给oTable 这样我们可以在后台方便地对表格进行刷新,获取选中行等操作。
var oTable = $('#dataTables-AccountList').DataTable({ 
            lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]],
            searching: false,//是否显示查询
            lengthChange: false,//是否使用下位列表选择分页大小
            //ordering:false,//全部禁止排序
            paginationType: "full_numbers",//分页按钮:有精简和全功能几种选项
            //语言国际化设置,默认是英文的
            language: {
                lengthMenu: "显示 _MENU_ 记录",//[[10, 25, 50, -1], [10, 25, 50, "All"]], //"显示 _MENU_ 记录",
                zeroRecords: "没有找到记录",
                info: "每页显示 10 条 当前显示 _START_ 到 _END_ 条,第 <span style='color:red'>_PAGE_</span> 页 ( 总共 _PAGES_ 页 ) 共 _TOTAL_ 条记录",
                infoEmpty: "没有找到记录",
                infoFiltered: "(从 _MAX_ 条记录过滤)",
                paginate: {
                    first: "首页",
                    previous: " 上一页",
                    next: " 下一页 ",
                    last: " 尾页 "
                },
                search: "模糊查询:" //查询按钮显示的文本
            },
            //表络绑定的字段 通过 render 方法可以对单元格内容进行格式化操作
            columns: [
               {
                   data: null, render: function (data, type, row) {
                       return "<input type='checkbox' num='" + data.ID + "' class='checkitem' name='checkitem' />";
                   }
               },
          { data: "YM" },
          { data: "Describ" },
          { data: "AccountTypeName" },
          { data: "Amount" },
          { data: "CategoryName" },
          { data: "AccountTime" },
          { data: "Name" },
          { data: "CreateDate" }
            ],
            //设置默认排序列
            sorting: [
               [6, "desc"]
            ],
            //对列进行一些特殊设置 比如禁止排序
            columnDefs: [{
                orderable: false,//禁用排序
                targets: [0, 2, 3, 5]   //指定的列 [0,4]
            }],
            select: true,//是否开启可以选中行 
            deferLoading: 2,//延迟加载
            ajaxSource: "/Accounts/Ajax_GetAccountList",//请求后台服务的地址
            serverData: questServerData, //向后台服务端传递的参数,在这里通过一个后调函数来操作的
            processing: true,//是否显示处理提示框 
            serverSide: true //如果是能通过后端获取的数据 则需求设置为True
        });


 questServerData 函数如下:


 function questServerData(sSource, aoData, fnCallback) {
            //将客户名称加入参数数组
            $.ajax({
                type: "POST",
                url: sSource,
                dataType: "json",//json
                data: "jsonparam=" + JSON.stringify(aoData) + "&startTime=" + $("#txtStartTime").val() + "&endTime=" + $("#txtEndTime").val() + "&category=" + $("#ddlcategory").val() + "&keyWords=" + $("#txtkeyWords").val(), //以json格式传递(struts2后台还是以string类型接受),year和month直接作为参数传递。
                error: function (request) {
                    //alertlogout(); //出错时一些处理
                    return false;
                },
                success: function (respresult) {
                    fnCallback(respresult); //服务器端返回的对象的returnObject部分是要求的格式
                    //翻页后清除选中行
                    $("#chk_all").attr("checked", false);
                    oTable.rows({ selected: true }).deselect();
                    oTable.cells({ selected: true }).deselect();
                }
            });
        }


 需要说明的是datatables 的分页相关的参数,如果 当前页,每页大小,排序字段等信息是包含在“aoData”json对象中的,通过 JSON.stringify 函数,将aoData 转换成post  参数传递给服务端。特此,在后端定义了一个公共类来处理这些信息如下:


   实体类
   public class DataTableJsonParam
    {
        public DataTableJsonParam();


        public int iColumns { get; set; }
        //分页大小相当于PageSize
        public int iDisplayLength { get; set; } 
        //当前页起始位置 相关于 StartIndex
        public int iDisplayStart { get; set; }
        public int iSortCol_0 { get; set; }
        public int iSortingCols { get; set; }
        public string sColumns { get; set; }
        public string sEcho { get; set; }
        public string sSearch { get; set; }
        //当前排序的列名
        public string sSortColumn { get; set; }
        public string sSortDir_0 { get; set; }
    }


方法:
public static T DataTableJsonParamFromJson<T>(string strjson)
        {
            Type _type = typeof(T);


            T t = (T)Activator.CreateInstance(_type);           


            JsonHelper _jsonhelper = new JsonHelper();


            if (string.IsNullOrEmpty(strjson))
                throw new NullReferenceException("strjson 参数为空");


            #region 定义正则


            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"{[^{}]+}", System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
            System.Text.RegularExpressions.Match math = reg.Match(strjson);


            #endregion


            Dictionary<int, string> _s_columns_list = new Dictionary<int, string>();


            #region 字段赋值


            while (math.Success)
            {
                string _strjson = math.Groups[0].Value;
                Dictionary<string, string> value = _jsonhelper.FromJson<Dictionary<string, string>>(_strjson);


                System.Reflection.PropertyInfo pi = _type.GetProperty(value["name"]);


                if (pi != null)
                {
                    switch (pi.PropertyType.Name)
                    {
                        case "Int":
                        case "Int16":
                        case "Int32":
                            pi.SetValue(t, Int32.Parse(value["value"]), null);
                            break;
                        case "String":
                            pi.SetValue(t, value["value"], null);
                            break;
                        default:
                            pi.SetValue(t, value["value"], null);
                            break;
                    }
                }


                if (value["name"].StartsWith("mDataProp_"))
                {
                    string str_key = value["name"] + "";
                    string str_value = value["value"]+"";
                    _s_columns_list.Add(Int32.Parse(str_key.Replace("mDataProp_", "")), str_value);
                }


                math = math.NextMatch();
            }


            #endregion


            #region  获取字段


            List<string> columns_list = new List<string>();
            foreach (int key in _s_columns_list.Keys)
            {
                string v_d = string.Empty;
                _s_columns_list.TryGetValue(key, out v_d);
                columns_list.Add(v_d);
            }


            //System.Reflection.PropertyInfo dcolumns_pi = _type.GetProperty("dColumns");
            //if (dcolumns_pi != null)
            //{
            //    dcolumns_pi.SetValue(t, columns_list.ToArray(), null);
            //}


            System.Reflection.PropertyInfo scolumns_pi = _type.GetProperty("sColumns");
            if (scolumns_pi != null)
            {
                scolumns_pi.SetValue(t, string.Join(",", columns_list.ToArray()), null);
            }




            System.Reflection.PropertyInfo ssortcolumnname_pi = _type.GetProperty("sSortColumn");
            if (ssortcolumnname_pi != null)
            {
                System.Reflection.PropertyInfo isortcol_0_pi = _type.GetProperty("iSortCol_0");
                if (isortcol_0_pi != null)
                    ssortcolumnname_pi.SetValue(t, 
                        columns_list.ToArray()[Convert.ToInt32(isortcol_0_pi.GetValue(t, null))], null);
            }


            #endregion


            return t;
        }


后端获取数据生成Json 的方法如下:


public string Ajax_GetAccountList(string startTime, string endTime,
            string category, string keyWords,string jsonparam)
        {
            StringPlus str_json = new StringPlus();


            DataTableJsonParam djsonp = new DataTableJsonParam();


            if (!string.IsNullOrEmpty(jsonparam))
            {
                djsonp = XHelper.DataTableJsonParamFromJson<DataTableJsonParam>(jsonparam);
            }


            startTime = Convert.ToDateTime(startTime).ToString("yyyy-MM-dd 00:00:00");
            endTime = Convert.ToDateTime(endTime).ToString("yyyy-MM-dd 23:59:59");


            int pageSize = djsonp.iDisplayLength;
            int startIndex = djsonp.iDisplayStart;
            int pageIndex = 1;


            //startIndex = (pageIndex - 1) * pageSize;
            pageIndex = startIndex / pageSize + 1; //获取当前页码


            List<string> Feilds = new List<string>();
            List<Condition> Condions = new List<Condition>();
            List<string> OrderBy = new List<string>();
            PageLimit Pager = new PageLimit();
            Pager.PageSize = pageSize;
            Pager.PageIndex = pageIndex;


            Feilds.Add("ID");
            Feilds.Add("YM");
            Feilds.Add("Describ");
            Feilds.Add("AccountType");
            Feilds.Add("AccountTypeName");           
            Feilds.Add("CategoryName");
            Feilds.Add("Amount");
            Feilds.Add("AmountText");
            Feilds.Add("AccountTime");
            Feilds.Add("DText");
            Feilds.Add("Name");           
            Feilds.Add("CreateDate");
                        
            if (!string.IsNullOrEmpty(startTime))
            {
                Condions.Add(new Condition() { Field = "CreateDate", Value = startTime, Comparison = ">=", Relation = "AND" });
            }
            if (!string.IsNullOrEmpty(endTime))
            {
                Condions.Add(new Condition() { Field = "CreateDate", Value = endTime, Comparison = "<=", Relation = "AND" });
            }
            if (!string.IsNullOrEmpty(category) && category != "00000")
            {
                Condions.Add(new Condition() { Field = "AccountType", Value = category, Comparison = "=", Relation = "AND" });
            }
            if (!string.IsNullOrEmpty(keyWords))
            {
                Condions.Add(new Condition() { Field = "Describ", Value = "like '" + keyWords + "'% ", Comparison = "=", Relation = "AND" });
            }


            if (!string.IsNullOrEmpty(djsonp.sSortColumn))
            {
                OrderBy.Add("" + djsonp.sSortColumn + " " + djsonp.sSortDir_0 + "");
            }
            else
            {
                OrderBy.Add("CreateDate ASC");
            }


            var rvl = _AccountsBLL.Find_Accounts_List(Feilds, Condions, OrderBy, Pager);
            string xdata = string.Empty;
            if (rvl.Status.Equals(OperationStatus.Success))
            {
                var list = rvl.DataList;
                xdata = XHelper.ToDataTableJson(list);
            }


            int recordsFiltered = Pager.RecordCount; //返回总查询到的记录数
            int recordsTotal = Pager.RecordCount; //返回总记录数


            str_json.Append("{\"recordsFiltered\":" + recordsFiltered + ",\"recordsTotal\":" + recordsTotal + ",\"data\": [" + xdata + "]}");


            return str_json.d;
        }




最终返回给前端的json 数据如下:
{
    "recordsFiltered": 11, //返回总查询到的记录数
    "recordsTotal": 11, //返回总记录数
    "data": [
        {
            "DT_RowId": "row_0",//行序号
            "ID": "209",
            "YM": "2016-01",
            "DText": "给家里寄钱买奶粉",
            "Describ": "给家里寄钱买奶粉",
            "Category": "6",
            "AccountType": "1",
            "AccountTypeName": "支出",
            "CategoryName": "个人消费",
            "Amount": "1500",
            "AmountText": "1500",
            "AccountTime": "2016-01-05 0:00:00",
            "CreateBy": "1",
            "CreateDate": "2016-01-05 21:34:17",
            "EncryptSign": "0",
            "EncryptSignText": "×",
            "DeleteSign": "0",
            "UserName": "wxd",
            "Name": "王晓东",
            "Role": "2",
            "MobilePhone": "15208312440",
            "NoteText": "给家里寄钱买奶粉",
            "TableName": "V_Accounts",
            "Properties": "System.String[]"
        },
        {
            "DT_RowId": "row_1",
            "ID": "216",
            "YM": "2016-01",
            "DText": "给老婆转帐",
            "Describ": "给老婆转帐",
            "Category": "6",
            "AccountType": "1",
            "AccountTypeName": "支出",
            "CategoryName": "个人消费",
            "Amount": "1000",
            "AmountText": "1000",
            "AccountTime": "2016-01-09 0:00:00",
            "CreateBy": "1",
            "CreateDate": "2016-01-09 19:02:58",
            "EncryptSign": "0",
            "EncryptSignText": "×",
            "DeleteSign": "0",
            "UserName": "wxd",
            "Name": "王晓东",
            "Role": "2",
            "MobilePhone": "15208312440",
            "NoteText": "给老婆转帐",
            "TableName": "V_Accounts",
            "Properties": "System.String[]"
        },
        ...
        {
            "DT_RowId": "row_9",
            "ID": "215",
            "YM": "2016-01",
            "DText": "看电影",
            "Describ": "看电影",
            "Category": "6",
            "AccountType": "1",
            "AccountTypeName": "支出",
            "CategoryName": "个人消费",
            "Amount": "18",
            "AmountText": "18",
            "AccountTime": "2016-01-09 0:00:00",
            "CreateBy": "1",
            "CreateDate": "2016-01-09 19:02:33",
            "EncryptSign": "0",
            "EncryptSignText": "×",
            "DeleteSign": "0",
            "UserName": "wxd",
            "Name": "王晓东",
            "Role": "2",
            "MobilePhone": "15208312440",
            "NoteText": "看电影加2元公交共18元",
            "TableName": "V_Accounts",
            "Properties": "System.String[]"
        }
    ]
}


这样jquery datatables 就为你自动呈现出漂亮,高端大气的表格:



 


最后我们看看jquery datatables 还需要掌握的一些函数和方法:
draw() : 生成表格的函数,当数据有变化时刷新表格,可以调用oTable的 draw方法
rows() : 获取行的函数,比如获取表格选中行 oTable.rows({ selected: true }) 获取选中行的ID标识 :oTable.rows({ selected: true }).data()[0].ID
deselect() : 删除选中对象 比如:oTable.rows({ selected: true }).deselect() 删除所有选中行  oTable.cells({ selected: true }).deselect() 删除所有选中单元格
rowCallback() : 生成行后回调函数。可以在行生成后附加一些特殊的操作
drawCallback() : 整个表格生成后的回调函数。


以上就是使用Jquery datatables 的最本方法,如果还想了解更高级的使用可以参照:http://datatables.net/ ,至此今天的分享结束。











0 0