jquery datatables 学习笔记
生活随笔
收集整理的這篇文章主要介紹了
jquery datatables 学习笔记
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
最近項目中用到了BootStrap做后臺,在選擇表格插件的時候發(fā)現(xiàn)了jquery datatables。
功能是很強大,但是網(wǎng)上的例子比較少。在經(jīng)過一段時間的努力可算是搞出來了。
官網(wǎng)地址:http://www.datatables.net/
官網(wǎng)上的例子比較簡單,基礎的介紹還是要看看的。
效果圖
?
引入相應css 和js?
<link href="http://cdn.datatables.net/1.10.5/css/jquery.dataTables.css" rel="stylesheet" /><script src="http://code.jquery.com/jquery-1.11.1.min.js"></script><script src="http://cdn.datatables.net/1.10.5/js/jquery.dataTables.min.js"></script>頁面HTML
<div class="portlet-body p10"><div class="form-body "><div class="row"><div class="col-md-5"><div class="form-group"><label class="control-label col-md-3">User Name: </label><div class="col-md-6"><input id="txt_UserName" name="txt_UserName" type="text" value="" /><span class="help-block">This is inline help </span></div></div></div><!--/span--><div class="col-md-5"><div class="form-group"><label class="control-label col-md-4">Division:</label><div class="col-md-6 form-inline"><select id="Sel_Division" name="Gender"><option value="">全部</option><option value="A">A</option><option value="B">B</option></select></div></div></div><!--/span--></div><div class="row"><div class="col-md-5"></div><!--/span--><div class="col-md-5"><div class="form-group"><button type="submit" id="btn_Search" class="btn green">Search</button></div></div><!--/span--></div></div></div><div class="portlet-body p10"><table class="table table-striped table-bordered table-hover" id="UserList"><thead><tr><th>User ID</th><th>User Ename</th><th>AD Account</th><th>User Email</th><th>Division</th><th>Entity</th><th>IsValid</th><th>Operation</th></tr></thead></table></div>?
?
我這里用到的是 服務器端處理。(很少有人把數(shù)據(jù)全部取出來,讓js 處理的吧。。。)
JS 代碼 初始化
var oTable = null; var initUserList = function () {var table = $('#UserList'); if (oTable == null) { //僅第一次檢索時初始化Datatable oTable = table.dataTable({"bLengthChange": false, //改變每頁顯示數(shù)據(jù)數(shù)量"bFilter": false, //過濾功能"bProcessing": true, //開啟讀取服務器數(shù)據(jù)時顯示正在加載中……特別是大數(shù)據(jù)量的時候,開啟此功能比較好"bServerSide": true, //開啟服務器模式,使用服務器端處理配置datatable。注意:sAjaxSource參數(shù)也必須被給予為了給datatable源代碼來獲取所需的數(shù)據(jù)對于每個畫。 這個翻譯有點別扭。"iDisplayLength": 10,//每頁顯示10條數(shù)據(jù)//ajax地址 "sAjaxSource": "/Home/Home/GetUserList",// get地址//"sAjaxSource": "/Home/Home/UserListPost",// post地址"fnServerData": retrieveData,//執(zhí)行方法//默認排序"order": [[0, 'asc']//第一列正序 ],"lengthMenu": [[5, 15, 20, -1],[5, 15, 20, "All"] // change per page values here ],// set the initial value"pageLength": 10,//向服務器傳額外的參數(shù)"fnServerParams": function (aoData) {aoData.push({ "name": "UserName", "value": $('#txt_UserName').val() },//員工名字{ "name": "Division", "value": $('#Sel_Division').val() })//所處Division},//配置列要顯示的數(shù)據(jù)"columns": [{ "data": "User_ID" },{ "data": "User_Ename" },{ "data": "AD_Account" },{ "data": "User_Email" },{ "data": "Division" },{ "data": "Entity" },{ "data": "IsValid" },{ "data": "" }//操作按鈕列],//按鈕列"columnDefs": [//{// "targets": -2,//編輯// "data": null,// "defaultContent": "<button id='editrow' class='btn btn-primary' type='button'><i class='fa fa-edit'></i></button>"//}, {"targets": -1,//刪除"data": null,"defaultContent": "<button id='editrow' class='btn btn-primary' type='button'><i class='fa fa-edit'></i></button><button id='delrow' class='btn btn-primary' type='button'><i class='fa fa-trash-o'></i></button>"}] ,//語言配置--頁面顯示的文字"language": {"aria": {"sortAscending": ": activate to sort column ascending","sortDescending": ": activate to sort column descending"},"emptyTable": "No data available in table","info": "Showing _START_ to _END_ of _TOTAL_ entries","infoEmpty": "No entries found","infoFiltered": "(filtered1 from _MAX_ total entries)","lengthMenu": "Show _MENU_ entries","search": "Search:","zeroRecords": "No matching records found"}});}//刷新Datatable,會自動激發(fā)retrieveData oTable.fnDraw();// tableWrapper.find('.dataTables_length select').select2(); // initialize select2 dropdown }function retrieveData(sSource, aoData, fnCallback) {/* get 方法調(diào)用*/$.ajax({"type": "get","contentType": "application/json","url": sSource,"dataType": "json","data": aoData, "success": function (resp) {fnCallback(resp); //服務器端返回的對象的returnObject部分是要求的格式 }});/* Post 方法調(diào)用$.ajax({"type": "post","url": sSource,"dataType": "json","data": aoData,"success": function (resp) {fnCallback(resp); //服務器端返回的對象的returnObject部分是要求的格式 }});*/ }
?
? jQuery(document).ready(function () {initUserList()//搜索$("#btn_Search").click(function () {initUserList()})//按鈕的綁定事件要放到document或者其他父標簽上,因為元素是在datatable方法加載完成之后才顯示出來的//編輯$(".portlet-body").on('click', 'button#editrow', function () {var data = $("#UserList").DataTable().row($(this).parents("tr")).data();alert(data.User_Ename + "'s Division is: " + data.Division);});//刪除$(".portlet-body").on('click', 'button#delrow', function () {var data = $("#UserList").DataTable().row($(this).parents("tr")).data();alert("Do you want delete " + data.User_Ename + "?");});});?
后臺代碼
開啟后臺處理之后,每次翻頁、排序都會調(diào)用代碼中配置的地址:/Home/Home/GetUserList
回傳很多參數(shù),我們這里只用到這幾個:
頁面大小:iDisplayLength
開始數(shù):iDisplayStart(是開始數(shù)不是當前頁數(shù)...)
要排序的列序號:iSortCol_0(從零開始)
正序還是倒序:sSortDir_0(desc or asc)
獲取第一列列明:mDataProp_0(從零開始)
好了上代碼
[HttpGet]public string GetUserList(){//JsonConvert.PopulateObject(var re = new UserRequest();//獲取頁面大小if (string.IsNullOrWhiteSpace(Request["iDisplayLength"]))re.PageSize = 10; elsere.PageSize = int.Parse(Request["iDisplayLength"]);//獲取開始數(shù) 算出當前頁數(shù)if (string.IsNullOrWhiteSpace(Request["iDisplayStart"]))re.PageIndex = 1; elsere.PageIndex = (int.Parse(Request["iDisplayStart"]) / re.PageSize) + 1;//自定義的兩個參數(shù) Division和UserNameif (!string.IsNullOrWhiteSpace(Request["Division"]))re.Division = Request["Division"];if (!string.IsNullOrWhiteSpace(Request["UserName"]))re.User_Ename = Request["UserName"];//排序if (!string.IsNullOrWhiteSpace(Request["iSortCol_0"]) && !string.IsNullOrWhiteSpace(Request["sSortDir_0"]))re.OrderBy = Request[("mDataProp_" + Request["iSortCol_0"])];// +" " + Request["sSortDir_0"];elsere.OrderBy = Request[("mDataProp_0")];//正序還是倒序if(!string.IsNullOrWhiteSpace(Request["sSortDir_0"]))re.Isdesc=(Request["sSortDir_0"]=="descdesc"?true:false);var result = new DataResult();var data = this.AccountService.GetUserList(re);//獲取數(shù)據(jù)的方法result.recordsTotal = data.TotalItemCount;result.recordsFiltered = data.TotalItemCount;result.data = data;return JsonConvert.SerializeObject(result);} public class UserRequest : Request{public UserRequest() { Isdesc = false; }public string User_Ename { get; set; }public string Division { get; set; }public bool IsValid { get; set; }public long User_ID { get; set; }public string OrderBy { get; set; }public bool Isdesc { get; set; }}?
public class DataResult{public int draw { get; set; }public int recordsTotal { get; set; }public int recordsFiltered { get; set; }public object data;}
?
??
?基本就這些了。嘿嘿,本人技術稀爛,大神見笑了。
轉(zhuǎn)載于:https://www.cnblogs.com/178mz/p/4383519.html
總結(jié)
以上是生活随笔為你收集整理的jquery datatables 学习笔记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HDU-1102-Constructin
- 下一篇: 数据库管理之数据表管理(1)