最近群里有很多人询问有关DataTables的问题,所以就抽空写出此篇,希望能够为各位提供一些帮助。
在正式阅读正文之前,我需要先声明以下几点:
1.我不是DataTables的专业开发人员,DT也不是我的主攻方向,实际上我研究DT也就1个多礼拜。所以很多深层次的问题,可能我并不懂,这也不是本文的讨论范围。
2.要达到某个目的可能有很多种方式,所以我接下来提出的解决方式可能并不是专业、完美、高效的。如果您有更好的解决方法,请在后面跟帖,如果确实有效,那我感谢您,反之就当做是多个了解。知识在于交流和共享!
3.有的朋友可能会问,为什么要这么写?这段代码的用意是什么?...对于这些问题,我还是希望你直接去群里问方便些(QQ群号:170222260)。同时告诉您一个道理,这世界上很多事情都是这样,别人说100遍不如你做1遍有效果,很多问题只要你自己把那段代码注释掉或者把自己的想法加进去,你就自然而然的知晓答案了。
以下是正文:
部分代码如下:
复制代码
以上是生成第一张图片的DataTables初始化代码,后面的代码是DataTables初始化数据请求以及排序的java后台代码:
Action:
复制代码
ServiceImpl:
复制代码
最后附上一个很重要的Action,此Action中的get,set方法不要随意更改(包括方法名的大小写),因为我试过,更改了之后是取不到前台传过来的参数值的:
复制代码
最后感谢武汉-饭太稀-java朋友的提醒,添加了ListAction中缺少的getParamMap方法。
在正式阅读正文之前,我需要先声明以下几点:
1.我不是DataTables的专业开发人员,DT也不是我的主攻方向,实际上我研究DT也就1个多礼拜。所以很多深层次的问题,可能我并不懂,这也不是本文的讨论范围。
2.要达到某个目的可能有很多种方式,所以我接下来提出的解决方式可能并不是专业、完美、高效的。如果您有更好的解决方法,请在后面跟帖,如果确实有效,那我感谢您,反之就当做是多个了解。知识在于交流和共享!
3.有的朋友可能会问,为什么要这么写?这段代码的用意是什么?...对于这些问题,我还是希望你直接去群里问方便些(QQ群号:170222260)。同时告诉您一个道理,这世界上很多事情都是这样,别人说100遍不如你做1遍有效果,很多问题只要你自己把那段代码注释掉或者把自己的想法加进去,你就自然而然的知晓答案了。
以下是正文:
部分代码如下:
- var docrTable = $('#docrevisontable').dataTable({
- "bProcessing" : true, //DataTables载入数据时,是否显示‘进度’提示
- "bServerSide" : true, //是否启动服务器端数据导入
- "bStateSave" : true, //是否打开客户端状态记录功能,此功能在ajax刷新纪录的时候不会将个性化设定回复为初始化状态
- "bJQueryUI" : true, //是否使用 jQury的UI theme
- "sScrollY" : 450, //DataTables的高
- "sScrollX" : 820, //DataTables的宽
- "aLengthMenu" : [20, 40, 60], //更改显示记录数选项
- "iDisplayLength" : 40, //默认显示的记录数
- "bAutoWidth" : false, //是否自适应宽度
- //"bScrollInfinite" : false, //是否启动初始化滚动条
- "bScrollCollapse" : true, //是否开启DataTables的高度自适应,当数据条数不够分页数据条数的时候,插件高度是否随数据条数而改变
- "bPaginate" : true, //是否显示(应用)分页器
- "bInfo" : true, //是否显示页脚信息,DataTables插件左下角显示记录数
- "sPaginationType" : "full_numbers", //详细分页组,可以支持直接跳转到某页
- "bSort" : true, //是否启动各个字段的排序功能
- "aaSorting" : [[1, "asc"]], //默认的排序方式,第2列,升序排列
- "bFilter" : true, //是否启动过滤、搜索功能
- "aoColumns" : [{
- "mDataProp" : "USERID",
- "sDefaultContent" : "", //此列默认值为"",以防数据中没有此值,DataTables加载数据的时候报错
- "bVisible" : false //此列不显示
- }, {
- "mDataProp" : "USERNAME",
- "sTitle" : "用户名",
- "sDefaultContent" : "",
- "sClass" : "center"
- }, {
- "mDataProp" : "EMAIL",
- "sTitle" : "电子邮箱",
- "sDefaultContent" : "",
- "sClass" : "center"
- }, {
- "mDataProp" : "MOBILE",
- "sTitle" : "手机",
- "sDefaultContent" : "",
- "sClass" : "center"
- }, {
- "mDataProp" : "PHONE",
- "sTitle" : "座机",
- "sDefaultContent" : "",
- "sClass" : "center"
- }, {
- "mDataProp" : "NAME",
- "sTitle" : "姓名",
- "sDefaultContent" : "",
- "sClass" : "center"
- }, {
- "mDataProp" : "ISADMIN",
- "sTitle" : "用户权限",
- "sDefaultContent" : "",
- "sClass" : "center"
- }],
- "oLanguage": { //国际化配置
- "sProcessing" : "正在获取数据,请稍后...",
- "sLengthMenu" : "显示 _MENU_ 条",
- "sZeroRecords" : "没有您要搜索的内容",
- "sInfo" : "从 _START_ 到 _END_ 条记录 总记录数为 _TOTAL_ 条",
- "sInfoEmpty" : "记录数为0",
- "sInfoFiltered" : "(全部记录数 _MAX_ 条)",
- "sInfoPostFix" : "",
- "sSearch" : "搜索",
- "sUrl" : "",
- "oPaginate": {
- "sFirst" : "第一页",
- "sPrevious" : "上一页",
- "sNext" : "下一页",
- "sLast" : "最后一页"
- }
- },
-
- "fnRowCallback" : function(nRow, aData, iDisplayIndex) {
- /* 用来改写用户权限的 */
- if (aData.ISADMIN == '1')
- $('td:eq(5)', nRow).html('管理员');
- if (aData.ISADMIN == '2')
- $('td:eq(5)', nRow).html('资料下载');
- if (aData.ISADMIN == '3')
- $('td:eq(5)', nRow).html('一般用户');
-
- return nRow;
- },
-
- "sAjaxSource" : "../use/userList.do?now=" + new Date().getTime(),
- //服务器端,数据回调处理
- "fnServerData" : function(sSource, aDataSet, fnCallback) {
- $.ajax({
- "dataType" : 'json',
- "type" : "POST",
- "url" : sSource,
- "data" : aDataSet,
- "success" : fnCallback
- });
- }
- });
-
- $("#docrevisontable tbody").click(function(event) { //当点击表格内某一条记录的时候,会将此记录的cId和cName写入到隐藏域中
- $(docrTable.fnSettings().aoData).each(function() {
- $(this.nTr).removeClass('row_selected');
- });
- $(event.target.parentNode).addClass('row_selected');
- var aData = docrTable.fnGetData(event.target.parentNode);
-
- $("#userId").val(aData.USERID);
- $("#userN").val(aData.USERNAME);
- });
-
- $('#docrevisontable_filter').html('<span>用户管理列表');
- $('#docrevisontable_filter').append(' <input type="button" class="addBtn" id="addBut" value="创建"/>');
- $('#docrevisontable_filter').append(' <input type="button" class="addBtn" id="addBut" value="修改"/>');
- $('#docrevisontable_filter').append(' <input type="button" class="addBtn" id="addBut" value="删除"/>');
- $('#docrevisontable_filter').append('</span>');
- }
Action:
- public class UserListAction extends ListAction {
- private ListService userServiceList;
-
- public ListService getUserServiceList() {
- return userServiceList;
- }
- public void setUserServiceList(ListService userServiceList) {
- this.userServiceList = userServiceList;
- }
-
- private static List<String> getColumnList(){
- List columnList = new ArrayList();
-
- columnList.add("user_id");
- columnList.add("user_name");
- columnList.add("email");
- columnList.add("mobile");
- columnList.add("phone");
- columnList.add("name");
- columnList.add("isadmin");
-
- return columnList;
- }
- public void getList() {
- try {
- Map<String, String> map = super.getParamMap();
-
- int len = Integer.parseInt(map.get("iDisplayLength") == null ? "0" : map.get("iDisplayLength")); //每页显示多少条数据
-
- int limt = Integer.parseInt(map.get("iDisplayStart") == null ? "0" : map.get("iDisplayStart")); //当前页的第一条纪录的索引号
-
- String orderCol = getColumnList().get(Integer.parseInt(map.get("iSortCol_0"))); //排序字段
-
- String sSortDir_0 = map.get("sSortDir_0"); //升、降序
-
- String sSearch = map.get("sSearch"); //搜索关键字
-
- List list = this.getUserServiceList().getPagingDataList(map, len, limt, orderCol, sSortDir_0);
-
- Map returnMap = new HashMap();
-
- returnMap.put("sEcho", super.getSEcho());
- returnMap.put("iTotalRecords", this.getUserServiceList().getCount(null));
- returnMap.put("iTotalDisplayRecords", this.getUserServiceList().getCount(null));
- returnMap.put("aaData", list);
-
- super.outJson(returnMap);
- } catch (Exception e) {
- Logger.error(e.getMessage());
-
- Map map = new HashMap();
-
- map.put("sEcho", super.getSEcho());
- map.put("iTotalRecords", 0);
- map.put("iTotalDisplayRecords", 0);
- map.put("aaData", new ArrayList());
-
- super.outJson(map);
- }
- }
- }
- /**
- * “用户管理”页的DataTables获取数据的ServiceImpl
- */
- public class UserListServiceImpl implements ListService {
- public List getPagingDataList(Map map, int len, int limt, String orderCol,String orderWay) {
- 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");
- SqlBuilder.FROM("t_users a");
- SqlBuilder.ORDER_BY(orderCol + " " + orderWay);
-
- String sql = SqlBuilder.SQL();
-
- List list = DBUtils.executeSelectDynamic(sql, len, limt);
-
- return list;
- }
- public int getCount(Map map) {
- return Integer.parseInt(String.valueOf(((Map) DBUtils.executeSelectDynamic("select count(*) as count from t_users").get(0)).get("COUNT")));
- }
- }
- /**
- * 用于获取前台DataTables插件一些参数的Action
- */
- public class ListAction extends BaseAction {
- private String iSortCol_0; //排序字段所对应的索引号
- private String sSortDir_0; //排序字段的排序方式,升、降序
- private String iDisplayLength; //默认显示的记录数
- private String iDisplayStart; //当前页的第一条纪录的索引号
- private String sSearch; //用于搜索的关键字
- private String sEcho; //当前页面的第N次请求数据
- private String iSortingCols;
- private String iSortCol_;
-
- public String getISortCol_0() {
- return iSortCol_0;
- }
- public void setISortCol_0(String sortCol_0) {
- iSortCol_0 = sortCol_0;
- }
-
- public String getSSortDir_0() {
- return sSortDir_0;
- }
- public void setSSortDir_0(String sortDir_0) {
- sSortDir_0 = sortDir_0;
- }
- public String getIDisplayLength() {
- return iDisplayLength;
- }
- public void setIDisplayLength(String displayLength) {
- iDisplayLength = displayLength;
- }
-
- public String getIDisplayStart() {
- return iDisplayStart;
- }
- public void setIDisplayStart(String displayStart) {
- iDisplayStart = displayStart;
- }
-
- public String getSSearch() {
- return sSearch;
- }
- public void setSSearch(String search) {
- sSearch = search;
- }
-
- public String getSEcho() {
- return sEcho;
- }
- public void setSEcho(String echo) {
- sEcho = echo;
- }
-
- public String getISortingCols() {
- return iSortingCols;
- }
- public void setISortingCols(String sortingCols) {
- iSortingCols = sortingCols;
- }
-
- public String getISortCol_() {
- return iSortCol_;
- }
- public void setISortCol_(String sortCol_) {
- iSortCol_ = sortCol_;
- }
- public Map<String, String> getParamMap() {
- Map map = new HashMap();
-
- map.put("iSortCol_0", this.getISortCol_0());
- map.put("sSortDir_0", this.getSSortDir_0());
- map.put("iDisplayLength", this.getIDisplayLength());
- map.put("iDisplayStart", this.getIDisplayStart());
- map.put("sSearch", this.getSSearch());
- map.put("sEcho", this.getSEcho());
- return map;
- }
- protected void outString(String str) {
- try {
- this.getResponse().setContentType("text/html;charset=UTF-8");
- PrintWriter out = getResponse().getWriter();
- Logger.debug(str);
- out.write(str);
- } catch (IOException e) {
- Logger.error(e.getMessage());
- }
- }
- }
顺带说一句,很多人不习惯使用firebug跟进去看具体内容,这样会造成很多时候看的云里雾里的。下面我放一些firebug的截图上来,其实对着自己的firebug看一下,很多简单的问题就自然揭晓了。
最后感谢武汉-饭太稀-java朋友的提醒,添加了ListAction中缺少的getParamMap方法。