增强型表格/报表-jqGrid使用浅析

 jqGrid是一个基于Jquery的表格插件,官网地址:http://www.trirand.com/blog演示地址:http://www.trirand.com/jqgrid/jqgrid.html大家可以去下载开发包,使用这个插件又需要jquery-ui,所以这个组件也是必须的。 
    和众多juery插件一样,这款插件的后台代码也是PHP的,而实际项目中使用的Struts2,我不得不又一次翻译代码并集成到Struts2中,后台和js交互的数据类型是json,这就需要一个json处理类来负责数据格式的转换。 
    前端必须的css是:ui.jqgrid.css 在jqGrid中;jquery-ui.css 在jquery-ui中 
    必须的js是:jquery.js jquery.jqGrid.js grid.locale-cn.js 最后一个是中文资源文件,其实我是按照英文文件自己翻译过来的 
    若需要日期选择框,还需要ui.datepicker.css ui.datepicker.js 
   下面是代码说明: 
HTML代码: 

Html代码  收藏代码
  1. <table id="list" class="scroll" width="100%"></table>  
  2. <div id="paging" class="scroll" style="text-align: center;"></div>  


Table是这个插件使用的原始HTML的table,div来用于显示分页。Id值是自定义的,这个只要和js代码中的相关配置一致即可,都没什么说的,class是这个组件css中的样式 
JS代码: 

Js代码  收藏代码
  1. <script type="text/javascript">   
  2. var lastsel;  
  3. jQuery("#list").jqGrid({  
  4.     url:'${base}/manage/user/userlist.action',  
  5.     datatype: 'json',  
  6.     autotrue,  
  7.     height:220,  
  8.     rownumbers: true,  
  9.     colNames:['用户ID','登录名','真实名','性别','生日'],  
  10.     colModel:[    
  11.         {name:'userId',index:'userId', 55,align:'center'},      
  12.         {name:'userName',index:'userName', 55,align:'center',editable:true},    
  13.         {name:'realName',index:'realName', 55,align:'center',editable:true},    
  14.         {name:'sex',index:'sex', 55,align:'center',editable:true,edittype:"select",editoptions:{value:"男:男;女:女"}},  
  15.         {name:'birthday',index:'birthday', 55,align:'center',editable:true,sorttype:"date"}  
  16.     ],  
  17.     rowNum:10,  
  18.     rowList:[10,20,30],  
  19.     imgpath: 'css3/images',  
  20.     pager: jQuery('#paging'),  
  21.     sortname: 'id',  
  22.     sortorder: "desc",  
  23.     multiselect: true,  
  24.     caption:"用户列表",  
  25.     onSelectRow: function(id){  
  26.         if(id && id!==lastsel){  
  27.             jQuery('#list').restoreRow(lastsel);  
  28.             jQuery('#list').editRow(id,true,pickdates);  
  29.             lastsel=id;  
  30.         }  
  31.     },  
  32.     editurl:" ${base}/manage/user/user!edit.action",  
  33. }).navGrid("#paging",{edit:false,add:true,del:true});  
  34.    
  35. function pickdates(id){  
  36.     jQuery("#"+id+"_birthday","#list").datepicker({dateFormat:"yy-mm-dd"});  
  37. }  
  38. </script>  


代码解释: 
url是后台数据传送过来的地址,这里我用Struts2,没什么好说的了 
datatype使用的是json,官方演示中还可以使用xml和js数组等,可以参考 
autowidth按字面意思理解即可,列宽度自适应 
hight就是控件的现实高度了 
rownumbers指定是否给显示从1开始的编号 
colNames是表头显示的内容了 
colModel就是具体数据的显示了这里可以参考官方演示,非常详细 
需要说明的是editable,该列是否可编辑 edittype指定可编辑的类型 
RowNum指定每次显示的数据量 
RowList是可选的现实数据量 
Imgpath 还没琢磨明白具体的含义 
Pager 就是分页了,上面指定过的div那层 
sortname排序的依据列 
sortorder 排序方式 
multiselect 是否可以多选,用于批量删除 
caption 表格的标题显示(这里的文字只能左对齐,我还没有找到居中的做法,还请高手赐教) 
onSelectRow就是当选定一行时,执行什么操作,这里是选定时将表格变为input可编辑效果 
editurl是做更新操作时的请求地址,那么在这个方法中区分是更新还是删除了 
下面的js函数就是做日期选择用的了。 
下面是后台代码说明: 

Java代码  收藏代码
  1. /** 
  2.      * 显示用户列表,封装为JsonView类型,前端使用jqGrid插件。设置的变量名都不得更改 
  3.      * 集合类均使用泛型 
  4.      * @author Sarin 
  5.      */  
  6.     public String userlist() {  
  7.         //准备jqGrid分页参数  
  8.         int total_pages = 0;  
  9.         int limit = Integer.parseInt(rows);  
  10.         int t_page = Integer.parseInt(page);  
  11.         if (sidx == null) {  
  12.             sidx = "userId";  
  13.         }  
  14.         //查询需要分页数据的总记录数  
  15.         int count = Integer.parseInt(getServMgr().getUserService().getUsersCount());  
  16.         //计算分页参数  
  17.         if (count > 0) {  
  18.             total_pages = (int) Math.ceil(count / limit) + 1;  
  19.         }  
  20.         if (t_page > total_pages) {  
  21.             t_page = total_pages;  
  22.         }  
  23.         int start = limit * t_page - limit;  
  24.         //获取记录列表  
  25.         List users = getServMgr().getUserService().getAllUsers(sidx + " " + sord, start, limit);  
  26.         List<Map> rows = new ArrayList<Map>();  
  27.         for (int i = 0; i < users.size(); i++) {  
  28.             Map<String, Object> map = new HashMap<String, Object>();  
  29.             //封装jqGrid可识别的数据格式  
  30.             Object[] cell = new Object[] { ((Map) users.get(i)).get("USERID"), ((Map) users.get(i)).get("USERNAME"),  
  31.                     ((Map) users.get(i)).get("REALNAME"), ((Map) users.get(i)).get("SEX"),  
  32.                     ((Map) users.get(i)).get("BIRTHDAY") };  
  33.             map.put("id", ((Map) users.get(i)).get("USERID"));//设置更新时的更新依据,一般为主键  
  34.             map.put("cell", cell);  
  35.             rows.add(map);  
  36.         }  
  37.         //构建Json类型的数据,参数名不可为其他的  
  38.         JSONObject result = new JSONObject();  
  39.         result.put("total", total_pages);  
  40.         result.put("records", count);  
  41.         result.put("page", t_page);  
  42.         result.put("rows", rows);  
  43.         //封装成jsonView向客户端输出  
  44.         jsonView = new JsonView(result);  
  45.         return "userlist";  
  46.     }  


Struts2的配置 

Xml代码  收藏代码
  1. <result-types>  
  2.   <result-type name="jsonView" class="***.***.util.json.JsonResult" />  
  3. </result-types>  
  4.   
  5. <action name="userlist" class="***.***.action.UserAction" method="userlist">  
  6.     <result name="userlist" type="jsonView">  
  7.     <param name="jsonObjName">jsonView</param>  
  8.     </result>  
  9. </action>  


JsonResult源码 

Java代码  收藏代码
  1. package ***.***.util.json;  
  2.   
  3. import java.io.PrintWriter;  
  4. import javax.servlet.http.HttpServletResponse;  
  5. import org.apache.struts2.dispatcher.StrutsResultSupport;  
  6. import com.opensymphony.xwork2.ActionInvocation;  
  7.   
  8. public class JsonResult extends StrutsResultSupport {  
  9.     private String contentTypeName;  
  10.     private String jsonObjName = "";  
  11.     public void setContentTypeName(String contentTypeName) {  
  12.         this.contentTypeName = contentTypeName;  
  13.     }  
  14.     public void setJsonObjName(String jsonObjName) {  
  15.         this.jsonObjName = jsonObjName;  
  16.     }  
  17.     @Override  
  18.     protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {  
  19.         HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext().get(HTTP_RESPONSE);  
  20.         String contentType = conditionalParse(contentTypeName, invocation);  
  21.         if (contentType == null) {  
  22.             contentType = "text/json;charset=UTF-8";  
  23.         }  
  24.         response.setContentType(contentType);  
  25.         PrintWriter out = response.getWriter();  
  26.         JsonView result = (JsonView) invocation.getStack().findValue(jsonObjName);  
  27.         out.println(result);  
  28.         out.flush();  
  29.         out.close();  
  30.     }  
  31. }  


效果图: 

原文地址:https://www.cnblogs.com/huangcongcong/p/4753969.html