DataTables基本搭建攻略(后台分页)

来源:互联网 发布:中财网数据引擎 编辑:程序博客网 时间:2024/05/22 05:02
最近群里有很多人询问有关DataTables的问题,所以就抽空写出此篇,希望能够为各位提供一些帮助。

在正式阅读正文之前,我需要先声明以下几点:
1.我不是DataTables的专业开发人员,DT也不是我的主攻方向,实际上我研究DT也就1个多礼拜。所以很多深层次的问题,可能我并不懂,这也不是本文的讨论范围。
2.要达到某个目的可能有很多种方式,所以我接下来提出的解决方式可能并不是专业、完美、高效的。如果您有更好的解决方法,请在后面跟帖,如果确实有效,那我感谢您,反之就当做是多个了解。知识在于交流和共享!
3.有的朋友可能会问,为什么要这么写?这段代码的用意是什么?...对于这些问题,我还是希望你直接去群里问方便些(QQ群号:170222260)。同时告诉您一个道理,这世界上很多事情都是这样,别人说100遍不如你做1遍有效果,很多问题只要你自己把那段代码注释掉或者把自己的想法加进去,你就自然而然的知晓答案了。

以下是正文:

部分代码如下:
  1. var docrTable = $('#docrevisontable').dataTable({
  2.             "bProcessing" : true, //DataTables载入数据时,是否显示‘进度’提示
  3.             "bServerSide" : true, //是否启动服务器端数据导入
  4.             "bStateSave" : true, //是否打开客户端状态记录功能,此功能在ajax刷新纪录的时候不会将个性化设定回复为初始化状态
  5.             "bJQueryUI" : true, //是否使用 jQury的UI theme
  6.             "sScrollY" : 450, //DataTables的高
  7.             "sScrollX" : 820, //DataTables的宽
  8.             "aLengthMenu" : [20, 40, 60], //更改显示记录数选项
  9.             "iDisplayLength" : 40, //默认显示的记录数
  10.             "bAutoWidth" : false, //是否自适应宽度
  11.             //"bScrollInfinite" : false, //是否启动初始化滚动条
  12.             "bScrollCollapse" : true, //是否开启DataTables的高度自适应,当数据条数不够分页数据条数的时候,插件高度是否随数据条数而改变
  13.             "bPaginate" : true, //是否显示(应用)分页器
  14.             "bInfo" : true, //是否显示页脚信息,DataTables插件左下角显示记录数
  15.             "sPaginationType" : "full_numbers", //详细分页组,可以支持直接跳转到某页
  16.             "bSort" : true, //是否启动各个字段的排序功能
  17.             "aaSorting" : [[1, "asc"]], //默认的排序方式,第2列,升序排列
  18.             "bFilter" : true, //是否启动过滤、搜索功能
  19.                     "aoColumns" : [{
  20.                         "mDataProp" : "USERID",
  21.                         "sDefaultContent" : "", //此列默认值为"",以防数据中没有此值,DataTables加载数据的时候报错
  22.                         "bVisible" : false //此列不显示
  23.                     }, {
  24.                         "mDataProp" : "USERNAME",
  25.                         "sTitle" : "用户名",
  26.                         "sDefaultContent" : "",
  27.                         "sClass" : "center"
  28.                     }, {
  29.                         "mDataProp" : "EMAIL",
  30.                         "sTitle" : "电子邮箱",
  31.                         "sDefaultContent" : "",
  32.                         "sClass" : "center"
  33.                     }, {
  34.                         "mDataProp" : "MOBILE",
  35.                         "sTitle" : "手机",
  36.                         "sDefaultContent" : "",
  37.                         "sClass" : "center"
  38.                     }, {
  39.                         "mDataProp" : "PHONE",
  40.                         "sTitle" : "座机",
  41.                         "sDefaultContent" : "",
  42.                         "sClass" : "center"
  43.                     }, {
  44.                         "mDataProp" : "NAME",
  45.                         "sTitle" : "姓名",
  46.                         "sDefaultContent" : "",
  47.                         "sClass" : "center"
  48.                     }, {
  49.                         "mDataProp" : "ISADMIN",
  50.                         "sTitle" : "用户权限",
  51.                         "sDefaultContent" : "",
  52.                         "sClass" : "center"
  53.                     }],
  54.                     "oLanguage": { //国际化配置
  55.                 "sProcessing" : "正在获取数据,请稍后...",  
  56.                 "sLengthMenu" : "显示 _MENU_ 条",  
  57.                 "sZeroRecords" : "没有您要搜索的内容",  
  58.                 "sInfo" : "从 _START_ 到  _END_ 条记录 总记录数为 _TOTAL_ 条",  
  59.                 "sInfoEmpty" : "记录数为0",  
  60.                 "sInfoFiltered" : "(全部记录数 _MAX_ 条)",  
  61.                 "sInfoPostFix" : "",  
  62.                 "sSearch" : "搜索",  
  63.                 "sUrl" : "",  
  64.                 "oPaginate": {  
  65.                     "sFirst" : "第一页",  
  66.                     "sPrevious" : "上一页",  
  67.                     "sNext" : "下一页",  
  68.                     "sLast" : "最后一页"  
  69.                 }
  70.             },
  71.                     
  72.                     "fnRowCallback" : function(nRow, aData, iDisplayIndex) {
  73.                         /* 用来改写用户权限的 */
  74.                         if (aData.ISADMIN == '1')
  75.                             $('td:eq(5)', nRow).html('管理员');
  76.                         if (aData.ISADMIN == '2')
  77.                             $('td:eq(5)', nRow).html('资料下载');
  78.                         if (aData.ISADMIN == '3')
  79.                             $('td:eq(5)', nRow).html('一般用户');
  80.                         
  81.                         return nRow;
  82.                     },
  83.                     
  84.                     "sAjaxSource" : "../use/userList.do?now=" + new Date().getTime(),
  85.                         //服务器端,数据回调处理
  86.                             "fnServerData" : function(sSource, aDataSet, fnCallback) {
  87.                                 $.ajax({
  88.                                     "dataType" : 'json',
  89.                                     "type" : "POST",
  90.                                     "url" : sSource,
  91.                                     "data" : aDataSet,
  92.                                     "success" : fnCallback
  93.                                 });
  94.                             }
  95.                 });
  96.                
  97.                 $("#docrevisontable tbody").click(function(event) { //当点击表格内某一条记录的时候,会将此记录的cId和cName写入到隐藏域中
  98.                     $(docrTable.fnSettings().aoData).each(function() {
  99.                         $(this.nTr).removeClass('row_selected');
  100.                     });
  101.                     $(event.target.parentNode).addClass('row_selected');
  102.                     var aData = docrTable.fnGetData(event.target.parentNode);
  103.                     
  104.                     $("#userId").val(aData.USERID);
  105.                     $("#userN").val(aData.USERNAME);
  106.                 });
  107.                
  108.                 $('#docrevisontable_filter').html('<span>用户管理列表');
  109.                 $('#docrevisontable_filter').append('   <input type="button" class="addBtn" id="addBut" value="创建"/>');
  110.                 $('#docrevisontable_filter').append('   <input type="button" class="addBtn" id="addBut" value="修改"/>');
  111.                 $('#docrevisontable_filter').append('   <input type="button" class="addBtn" id="addBut" value="删除"/>');
  112.                 $('#docrevisontable_filter').append('</span>');
  113.         }
复制代码
以上是生成第一张图片的DataTables初始化代码,后面的代码是DataTables初始化数据请求以及排序的java后台代码:
Action:
  1. public class UserListAction extends ListAction {
  2.         private ListService userServiceList;
  3.         
  4.         public ListService getUserServiceList() {
  5.                 return userServiceList;
  6.         }

  7.         public void setUserServiceList(ListService userServiceList) {
  8.                 this.userServiceList = userServiceList;
  9.         }
  10.         
  11.         private static List<String> getColumnList(){
  12.                 List columnList = new ArrayList();
  13.                
  14.                 columnList.add("user_id");
  15.                 columnList.add("user_name");
  16.                 columnList.add("email");
  17.                 columnList.add("mobile");
  18.                 columnList.add("phone");
  19.                 columnList.add("name");
  20.                 columnList.add("isadmin");
  21.                
  22.                 return columnList;
  23.         }

  24.         public void getList() {
  25.                 try {
  26.                         Map<String, String> map = super.getParamMap();
  27.                         
  28.                         int len = Integer.parseInt(map.get("iDisplayLength") == null ? "0" : map.get("iDisplayLength")); //每页显示多少条数据
  29.                         
  30.                         int limt = Integer.parseInt(map.get("iDisplayStart") == null ? "0" : map.get("iDisplayStart")); //当前页的第一条纪录的索引号
  31.                         
  32.                         String orderCol = getColumnList().get(Integer.parseInt(map.get("iSortCol_0"))); //排序字段
  33.                         
  34.                         String sSortDir_0 = map.get("sSortDir_0"); //升、降序
  35.                         
  36.                         String sSearch = map.get("sSearch"); //搜索关键字
  37.                         
  38.                         List list = this.getUserServiceList().getPagingDataList(map, len, limt, orderCol, sSortDir_0);
  39.                         
  40.                         Map returnMap = new HashMap();
  41.                         
  42.                         returnMap.put("sEcho", super.getSEcho());
  43.                         returnMap.put("iTotalRecords", this.getUserServiceList().getCount(null));
  44.                         returnMap.put("iTotalDisplayRecords", this.getUserServiceList().getCount(null));
  45.                         returnMap.put("aaData", list);
  46.                         
  47.                         super.outJson(returnMap);
  48.                 } catch (Exception e) {
  49.                         Logger.error(e.getMessage());
  50.                         
  51.                         Map map = new HashMap();
  52.                         
  53.                         map.put("sEcho", super.getSEcho());
  54.                         map.put("iTotalRecords", 0);
  55.                         map.put("iTotalDisplayRecords", 0);
  56.                         map.put("aaData", new ArrayList());
  57.                         
  58.                         super.outJson(map);
  59.                 }
  60.         }
  61. }
复制代码
ServiceImpl:
  1. /**
  2. * “用户管理”页的DataTables获取数据的ServiceImpl
  3. */
  4. public class UserListServiceImpl implements ListService {
  5.         public List getPagingDataList(Map map, int len, int limt, String orderCol,String orderWay) {
  6.                 SqlBuilder.SELECT("a.user_id AS userId, a.user_name AS userName, a.email AS email, a.mobile AS mobile, a.phone AS phone, a.name AS name, a.isadmin AS isAdmin");
  7.                 SqlBuilder.FROM("t_users a");
  8.                 SqlBuilder.ORDER_BY(orderCol + " " + orderWay);
  9.             
  10.                 String sql = SqlBuilder.SQL();
  11.                
  12.                 List list = DBUtils.executeSelectDynamic(sql, len, limt);
  13.                
  14.                 return list;
  15.     }

  16.     public int getCount(Map map) {
  17.         return Integer.parseInt(String.valueOf(((Map) DBUtils.executeSelectDynamic("select count(*) as count from t_users").get(0)).get("COUNT")));
  18.     }
  19. }
复制代码
最后附上一个很重要的Action,此Action中的get,set方法不要随意更改(包括方法名的大小写),因为我试过,更改了之后是取不到前台传过来的参数值的:
  1. /**
  2. * 用于获取前台DataTables插件一些参数的Action
  3. */
  4. public class ListAction extends BaseAction {
  5.         private String iSortCol_0; //排序字段所对应的索引号
  6.         private String sSortDir_0; //排序字段的排序方式,升、降序
  7.         private String iDisplayLength; //默认显示的记录数
  8.         private String iDisplayStart; //当前页的第一条纪录的索引号
  9.         private String sSearch; //用于搜索的关键字
  10.         private String sEcho; //当前页面的第N次请求数据
  11.         private String iSortingCols;
  12.         private String iSortCol_;
  13.        
  14.         public String getISortCol_0() {
  15.     return iSortCol_0;
  16.         }

  17.         public void setISortCol_0(String sortCol_0) {
  18.     iSortCol_0 = sortCol_0;
  19.         }
  20.        
  21.         public String getSSortDir_0() {
  22.     return sSortDir_0;
  23.         }

  24.         public void setSSortDir_0(String sortDir_0) {
  25.     sSortDir_0 = sortDir_0;
  26.         }

  27.         public String getIDisplayLength() {
  28.     return iDisplayLength;
  29.         }

  30.         public void setIDisplayLength(String displayLength) {
  31.     iDisplayLength = displayLength;
  32.         }
  33.        
  34.         public String getIDisplayStart() {
  35.     return iDisplayStart;
  36.         }

  37.         public void setIDisplayStart(String displayStart) {
  38.     iDisplayStart = displayStart;
  39.         }
  40.        
  41.         public String getSSearch() {
  42.     return sSearch;
  43.         }

  44.         public void setSSearch(String search) {
  45.     sSearch = search;
  46.         }
  47.        
  48.         public String getSEcho() {
  49.     return sEcho;
  50.         }

  51.         public void setSEcho(String echo) {
  52.     sEcho = echo;
  53.         }
  54.        
  55.         public String getISortingCols() {
  56.     return iSortingCols;
  57.         }

  58.         public void setISortingCols(String sortingCols) {
  59.     iSortingCols = sortingCols;
  60.         }
  61.        
  62.         public String getISortCol_() {
  63.     return iSortCol_;
  64.         }

  65.         public void setISortCol_(String sortCol_) {
  66.     iSortCol_ = sortCol_;
  67.         }

  68.         public Map<String, String> getParamMap() {
  69.     Map map = new HashMap();
  70.                
  71.     map.put("iSortCol_0", this.getISortCol_0());
  72.     map.put("sSortDir_0", this.getSSortDir_0());
  73.     map.put("iDisplayLength", this.getIDisplayLength());
  74.     map.put("iDisplayStart", this.getIDisplayStart());
  75.     map.put("sSearch", this.getSSearch());
  76.     map.put("sEcho", this.getSEcho());

  77.     return map;
  78.         }

  79.         protected void outString(String str) {
  80.     try {
  81.         this.getResponse().setContentType("text/html;charset=UTF-8");
  82.         PrintWriter out = getResponse().getWriter();
  83.         Logger.debug(str);
  84.         out.write(str);
  85.     } catch (IOException e) {
  86.         Logger.error(e.getMessage());
  87.     }
  88.         }

  89. }
复制代码

顺带说一句,很多人不习惯使用firebug跟进去看具体内容,这样会造成很多时候看的云里雾里的。下面我放一些firebug的截图上来,其实对着自己的firebug看一下,很多简单的问题就自然揭晓了。


文章出处:http://www.javashen.com/forum.php?mod=viewthread&tid=1708&extra=page%3D1



最后感谢武汉-饭太稀-java朋友的提醒,添加了ListAction中缺少的getParamMap方法。