根据jqGrid的文档,要想生成一个jqGrid,最直接的方法就是:
$("#grid_id").jqGrid(options);
也就是通过选择符得到一个table的jQuery对象,然后调用jqGrid(options),得到一个jqGrid对象。
重点就在传入的option选项上了,通过这些选项可以得到各种各样的Grid表格。
1. jqGrid的重要选项
具体的options参考,可以访问jqGrid文档关于option的章节(http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options)。其中有几个是比较常用的,重点介绍一下:
1.1 prmNames选项
prmNames是jqGrid的一个重要选项,用于设置jqGrid将要向Server传递的参数名称。其默认值为:
prmNames : { page:"page", // 表示请求页码的参数名称 rows:"rows", // 表示请求行数的参数名称 sort: "sidx", // 表示用于排序的列名的参数名称 order: "sord", // 表示采用的排序方式的参数名称 search:"_search", // 表示是否是搜索请求的参数名称 nd:"nd", // 表示已经发送请求的次数的参数名称 id:"id", // 表示当在编辑数据模块中发送数据时,使用的id的名称 oper:"oper", // operation参数名称(我暂时还没用到) editoper:"edit", // 当在edit模式中提交数据时,操作的名称 addoper:"add", // 当在add模式中提交数据时,操作的名称 deloper:"del", // 当在delete模式中提交数据时,操作的名称 subgridid:"id", // 当点击以载入数据到子表时,传递的数据名称 npage: null, totalrows:"totalrows" // 表示需从Server得到总共多少行数据的参数名称,参见jqGrid选项中的rowTotal }
可以通过这个选项来自定义当向Server发送请求时,默认发送的参数名称。
这个参数很重要也很有用,正是通过这个参数,可以方便的改变默认的request的参数,以符合Server端的需要。比如在prmNames中search默认的值为"_search",这在Struts2的Action中不太方便命名成员变量和getter/ setter。因此可以使用 prmNames: {search: 'search'} 来改变这一默认值为"search",这在Struts2的Action对象中就很好设置getter/ setter了,即getSearch()和setSearch()。当然其他名字也是可以的。
1.2 jsonReader选项
jsonReader是jqGrid的一个重要选项,用于设置如何解析从Server端发回来的json数据。其默认值为:
jsonReader : { root: "rows", // json中代表实际模型数据的入口 page: "page", // json中代表当前页码的数据 total: "total", // json中代表页码总数的数据 records: "records", // json中代表数据行总数的数据 repeatitems: true, // 如果设为false,则jqGrid在解析json时,会根据name来搜索对应的数据元素(即可以json中元素可以不按顺序);而所使用的name是来自于colModel中的name设定。 cell: "cell", id: "id", userdata: "userdata", subgrid: { root:"rows", repeatitems: true, cell:"cell" } }
可以这样理解,prmNames设置了如何将Grid所需要的参数传给Server,而jsonReader设置了如何去解析从Server端传回来的json数据。如果没有设置jsonReader的话,jqGrid将会根据默认的设置来解析json数据,并显示在表格里。但如果传回来的json数据,不太符合默认设置(比如内部的结构名不太一样),那么就有必要修改这一设置。比如:
jsonReader: { root:"gridModel", page: "page", total: "total", records: "record", repeatitems : false }
注1:据其他网友的文章,如果设置repeatitems为false,不但数据可以乱序,而且不用每个数据元素都要具备,用到哪个找到哪个就可以了。实验却是如此。
注2:cell、id在repeatitems为true时可以用到,即每一个记录是由一对id和cell组合而成,即可以适用另一种json结构。援引文档中的例子:
repeatitems为true时:
jQuery("#gridid").jqGrid({ ... jsonReader : { root:"invdata", page: "currpage", total: "totalpages", records: "totalrecords" }, ... });
json结构为:
{ "totalpages": "xxx", "currpage": "yyy", "totalrecords": "zzz", "invdata" : [ {"id" :"1", "cell" :["cell11", "cell12", "cell13"]}, // cell中不需要各列的name,只要值就OK了,但是需要保持对应 {"id" :"2", "cell" :["cell21", "cell22", "cell23"]}, ... ] }
repeatitems为false时:
jQuery("#gridid").jqGrid({ ... jsonReader : { root:"invdata", page: "currpage", total: "totalpages", records: "totalrecords", repeatitems: false, id: "0" }, ... });
json结构为:
{ "totalpages" : "xxx", "currpage" : "yyy", "totalrecords" : "zzz", "invdata" : [ {"invid" : "1","invdate":"cell11", "amount" :"cell12", "tax" :"cell13", "total" :"1234", "note" :"somenote"}, // 数据中需要各列的name,但是可以不按列的顺序 {"invid" : "2","invdate":"cell21", "amount" :"cell22", "tax" :"cell23", "total" :"2345", "note" :"some note"}, ... ] }
2. colModel的重要选项
和jqGrid一样colModel也有许多非常重要的选项,在使用搜索、排序等方面都会用到。这里先只说说最基本的。
3. 第一个实例
3.1 服务器端
用于提供数据的Action。为了可以复用这种专门接受jqGrid传来参数的Action,我抽象出一个基本类。具体代码如下:
package cn.gengv.struts2ex.jqGrid; import java.util.Collections; import java.util.List; import com.opensymphony.xwork2.ActionSupport; @SuppressWarnings("serial") public abstract class JqGridBaseAction<T> extends ActionSupport { // 和jqGrid组件相关的参数属性 private List<T> gridModel = Collections.emptyList(); private Integer rows = 0; private Integer page = 0; private Integer total = 0; private Integer record = 0; private String sord; private String sidx; private String search; public abstract int getResultSize(); public abstract List<T> listResults(int from, int length); public String refreshGridModel() { try { List<T> results = Collections.emptyList(); record = this.getResultSize(); int from = rows * (page - 1); int length = rows; results = this.listResults(from, length); this.setGridModel(results); total = (int) Math.ceil((double) record / (double) rows); return SUCCESS; } catch (Exception e) { e.printStackTrace(); this.addActionError(e.getMessage()); return ERROR; } } public List<T> getGridModel() { return gridModel; } public void setGridModel(List<T> gridModel) { this.gridModel = gridModel; } public Integer getRows() { return rows; } public void setRows(Integer rows) { this.rows = rows; } public Integer getPage() { return page; } public void setPage(Integer page) { this.page = page; } public Integer getTotal() { return total; } public void setTotal(Integer total) { this.total = total; } public Integer getRecord() { return record; } public void setRecord(Integer record) { this.record = record; } public String getSord() { return sord; } public void setSord(String sord) { this.sord = sord; } public String getSidx() { return sidx; } public void setSidx(String sidx) { this.sidx = sidx; } public String getSearch() { return search; } public void setSearch(String search) { this.search = search; } }
说明:
成员变量 | 对应 prmNames | 对应 jsonReader | 注释 |
rows | rows | - | 每页中现实的记录行数 |
search | search | - | 是否是用于查询的请求 |
sidx | sort | - | 用于排序的列名 |
sord | order | - | 排序的方式 |
page | page | page | 当前页码 |
gridModel | - | root | 用于得到实际数据的数组名称 |
total | - | total | 总页数 |
record | - | records | 总记录数 |
具体的一个实现类:
package cn.gengv.struts2ex.jqGrid; import java.util.Collections; import java.util.List; @SuppressWarnings("serial") public class ListContactsAction extends JqGridBaseAction<Contact> { private ContactService contactService; @Override public String execute() { return this.refreshGridModel(); } @Override public int getResultSize() { return this.contactService.queryResultsCount(); } @Override public List<Contact> listResults(int from, int length) { List<Contact> results = Collections.emptyList(); results = this.contactService.queryByPage(from, length); return results; } public void setContactService(ContactService contactService) { this.contactService = contactService; } }
而在struts.xml中,应按如下设置配置action:
<action name="jqGrid01" class="cn.gengv.struts2ex.jqGrid.ListContactsAction"> <result name="success" type="json"> <param name="includeProperties"> ^gridModel/[/d+/]/./w+, rows, page, total, record </param> <param name="noCache">true</param> <param name="ignoreHierarchy">false</param> </result> </action>
3.2 客户端(浏览器)
javascript部分:
$(function(){ // 配置jqGrid组件 $("#gridTable").jqGrid({ url: "jqGrid01.action", datatype: "json", mtype: "GET", height: 350, autowidth: true, colModel: [ {name:"id",index:"id",label:"ID",width:40}, {name:"lastName",index:"lastName",label:"Last Name",width:80,sortable:false}, {name:"firstName",index:"firstName",label:"First Name",width:80,sortable:false}, {name:"email",index:"email",label:"E-mail",width:160,sortable:false}, {name:"telNo",index:"telNo",label:"Tel No",width:120,sortable:false} ], viewrecords: true, rowNum: 15, rowList: [15,50,100], prmNames: {search: "search"}, //(1) jsonReader: { root:"gridModel", // (2) records: "record", // (3) repeatitems : false // (4) }, pager: "#gridPager", caption: "联系人列表", hidegrid: false }); });
其中主要的选项在开头已经介绍过了,另外需要说明以下几点:
1、在位置(1)处,为了配合Server端的Action类中的成员变量命名,将prmNames中search对应的“_search”更改为“search”。
2、在位置(2)(3)处,为了配合Server端的Action类中的成员变量命名,将jsonReader中root对应的“rows”更改为“gridModel”,将records对应的“records”更改为“record”。
在后面的request和response解析中,就可以看到这些更改的作用。
html部分:
要想顺利的使用jqGrid,需要想页面中引入6个文件,其中4个js文件,2个css文件。它们分别是:
注 :jqGrid的官方包中原本针对中文的locale js文件是grid.locale-cn.js,但是里面的某些设置,并没有做到完全中文化,因此我从Struts2-jQuery插件中分离出grid.locale-zh-CN.js和jquery.ui.datepicker-zh-CN.min.js这两个文件以备后用。说起来这两个文件中,针对中文的设置还是不错的。
引入这6个文件后,创建jqGrid的工作就交给上面写的javascript代码来完成了。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN" lang="zh-CN"> <head> <title>jqGrid01</title> <link rel="stylesheet" type="text/css" media="screen" href="../css/themes/aero/jquery-ui-1.8.1.custom.css" mce_href="css/themes/aero/jquery-ui-1.8.1.custom.css" /> <link rel="stylesheet" type="text/css" media="screen" href="../css/themes/aero/ui.jqgrid.custom.css" mce_href="css/themes/aero/ui.jqgrid.custom.css" /> <mce:script type="text/javascript" src="../js/jquery-1.4.2.min.js" mce_src="js/jquery-1.4.2.min.js"></mce:script> <mce:script src="../js/jquery-ui-1.8.1.custom.min.js" mce_src="js/jquery-ui-1.8.1.custom.min.js" type="text/javascript"></mce:script> <mce:script src="../js/i18n/grid.locale-zh-CN.js" mce_src="js/i18n/grid.locale-zh-CN.js" type="text/javascript"></mce:script> <mce:script src="../js/jquery.jqGrid.min.js" mce_src="js/jquery.jqGrid.min.js" type="text/javascript"></mce:script> <mce:script src="js/jqGrid01.js" mce_src="js/jqGrid01.js" type="text/javascript"></mce:script> </head> <body> <h2> jqGrid测试 01 </h2> <div> <table id="gridTable"></table> <div id="gridPager"></div> </div> </body> </html>
HTML中的代码,异常简洁。
3.3 整个流程
通过Firebug监测request和response就可以看出Server和浏览器之间的数据交互。当打开页面的时候,jqGrid初始化,会向Server发送url中定义的request,并传递参数。如下:
http://localhost:8085/Hare/jqGridTest/jqGrid01.action?search=false&nd=1278331032140&rows=15&page=1&sidx=&sord=asc
jqGrid会根据prmNames中的定义,向Server传递参数,例如将jqGrid选项中rowNum的值,作为参数rows传递到Server。
由于我将prmNames中的search设为“search”,所以参数里表中出现了这个参数;否则仍会根据原来的默认值,出现“_search”参数。
再看看response,Server发送来的json数据,格式是这样的:
{ "gridModel": [ { "address": "ADDR-yjfrot4i008toqlrl4dfq9", "email": "[email protected]", "firstName": "FN-gn7po9c9m", "fullName": "LN-3h6d1q FN-gn7po9c9m", "id": 23016, "idCardNo": "CARD-28ew6dekrv9g8dml4n", "lastName": "LN-3h6d1q", "nationality": "NAT-6z1xhty2", "telNo":: "TEL-x3i4a625i" }, { "address": "ADDR-9zeiasrr", "email": "[email protected]", "firstName": "FN-8mwhw7n", "fullName": "LN-yaontk FN-8mwhw7n", "id": 23015, "idCardNo": "CARD-gqqbd9s4zjexj05sus", "lastName": "LN-yaontk", "nationality": "NAT-0phliht", "telNo":: "TEL-jf4c31" }, { "address": "ADDR-o4ml00d98j7xgktl", "email": "[email protected]", "firstName": "FN-etzsxbaq4", "fullName": "LN-uedrek8 FN-etzsxbaq4", "id": 23014, "idCardNo": "CARD-md9bcyef7wvcc7om6b", "lastName": "LN-uedrek8", "nationality": "NAT-okbb5", "telNo":: "TEL-pp0d00" }, { "address": "ADDR-obzar7v7z58uux", "email": "[email protected]", "firstName": "FN-f1qnbw0x", "fullName": "LN-20ug4vxfc FN-f1qnbw0x", "id": 23013, "idCardNo": "CARD-kzil6hhtpo68izim0b", "lastName": "LN-20ug4vxfc", "nationality": "NAT-dxidrf", "telNo":: "TEL-eug8ydessk" }, { "address": "ADDR-r7954tumxw133a9os90l", "email": "[email protected]", "firstName": "FN-pw1yl8ux", "fullName": "LN-nk7qg6by FN-pw1yl8ux", "id": 23012, "idCardNo": "CARD-0cx02jpey6nivhkr29", "lastName": "LN-nk7qg6by", "nationality": "NAT-85tl0a", "telNo":: "TEL-4aa404" }, { "address": "ADDR-jxmudykwu7kcu", "email": "[email protected]", "firstName": "FN-cjxxxds3", "fullName": "LN-3iviu7o FN-cjxxxds3", "id": 23011, "idCardNo": "CARD-9evl3ul16uldvjango", "lastName": "LN-3iviu7o", "nationality": "NAT-v2gnaa9", "telNo":: "TEL-gzbn1w" }, { "address": "ADDR-9xsk62kmdidc", "email": "[email protected]", "firstName": "FN-iqygy07ku", "fullName": "LN-3mrxki FN-iqygy07ku", "id": 23010, "idCardNo": "CARD-ccypafwru43cqyjo62", "lastName": "LN-3mrxki", "nationality": "NAT-qjpvfa", "telNo":: "TEL-2bqxde" }, { "address": "ADDR-t8dizyumbedgbd0u8ml", "email": "[email protected]", "firstName": "FN-89xwf0", "fullName": "LN-8wr6uiig3 FN-89xwf0", "id": 23009, "idCardNo": "CARD-7t09x2dw3i3y78z24e", "lastName": "LN-8wr6uiig3", "nationality": "NAT-9uu7xo", "telNo":: "TEL-p8ym9rtwy" }, { "address": "ADDR-gupoe8jwcqwcjs2u01oa8", "email": "[email protected]", "firstName": "FN-0amkpy2", "fullName": "LN-i73kpz5nc FN-0amkpy2", "id": 23008, "idCardNo": "CARD-itgmrwwichkzan5220", "lastName": "LN-i73kpz5nc", "nationality": "NAT-k2aq2t", "telNo":: "TEL-2wdhbs" }, { "address": "ADDR-gp9q73fzs68agav6", "email": "[email protected]", "firstName": "FN-w42bd8y", "fullName": "LN-utrnn25c FN-w42bd8y", "id": 23007, "idCardNo": "CARD-rrznb3ihqf94k2wjkv", "lastName": "LN-utrnn25c", "nationality": "NAT-gs3e9rk", "telNo":: "TEL-g8j19nqz9" }, { "address": "ADDR-ja8w4gq485m3dn2gr66", "email": "[email protected]", "firstName": "FN-dxfyd5m5m", "fullName": "LN-li98bk FN-dxfyd5m5m", "id": 23006, "idCardNo": "CARD-indqfrmi13zfazly67", "lastName": "LN-li98bk", "nationality": "NAT-qglj9sx2", "telNo":: "TEL-mzlpe3m" }, { "address": "ADDR-rm3r94qanvt1q4drp", "email": "[email protected]", "firstName": "FN-qkq3w1m", "fullName": "LN-0j90sa FN-qkq3w1m", "id": 23005, "idCardNo": "CARD-8vc92wevyunbpl29c0", "lastName": "LN-0j90sa", "nationality": "NAT-mv2wzlt", "telNo":: "TEL-ntkah0" }, { "address": "ADDR-u3gsxpq61e2", "email": "[email protected]", "firstName": "FN-evno7jy", "fullName": "LN-0fuix09 FN-evno7jy", "id": 23004, "idCardNo": "CARD-jgyf09by0rxboex8ut", "lastName": "LN-0fuix09", "nationality": "NAT-cw8cctzy", "telNo":: "TEL-artsappc2" }, { "address": "ADDR-04kfdpp7", "email": "[email protected]", "firstName": "FN-zz0e74gvh", "fullName": "LN-26u851 FN-zz0e74gvh", "id": 23003, "idCardNo": "CARD-wminx9rykz1sn7xsxz", "lastName": "LN-26u851", "nationality": "NAT-05uk2c93", "telNo":: "TEL-9de2jt4oh", }, { "address": "ADDR-i18dy2cew6eizvmvgi0w", "email": "[email protected]", "firstName": "FN-gt4aice1", "fullName": "LN-db6vre9 FN-gt4aice1", "id": 23002, "idCardNo": "CARD-spwifyvehzkcfj5g7f", "lastName": "LN-db6vre9", "nationality": "NAT-osiionb", "telNo":: "TEL-1vigb907", } ], "page": 1, "record": 23013, "rows": 15, "total": 1535 }
jqGrid根据jsonReader中的设置,解析json数据。根据jsonReader中的root(我设置的是“gridModel”),得到数据记录数组;根据rows得到每页显示的行数;根据page设置当前页数;根据records(我设置的是“record”)得到所有记录数量;根据total得到所有页数。
由此,jqGrid完成一个request,并将得到的response,解析为所需的数据,显示到Grid表格中。