ExtJs表格控制項(一)
ExtJs表格由類Ext.grid.GridPanel定義,其xtype為grid。表格中列資訊由columns定義,而表格的資料存放區器由Ext.data.Store定義。
列的定義是一個JSON數組,這個JSON數字是整個表格列的模型必須首先定義,這個JSON數組中的每一個元素都是描述一列屬性的,包含:顯示文本(header)、列對應的記錄集欄位(dataIndex)、列的渲染函數(renderer)、寬度(width)以及格式化資訊(format)。
下面看一個具體樣本:
首先在JSP頁面中引入EXT相關的資源,並且引入自己寫的JS檔案,並且在頁面中個定義一個DIV,定義ID為grid。用於顯示寫成的表格。
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>My JSP 'index.jsp' starting page<script type="text/javascript" src="./extjs/ext-all.js"></script><script type="text/javascript" src="./extjs/ext-lang-zh_CN.js"></script><script type="text/javascript" src="./script/table.js"></script>
然後看table.js,在這個JS檔案中定義了columns和Store還有grid。
Ext.onReady(function() {//渲染函數var datarender = function(value){return ""+value+"";};var columns = [ {header : '第一列',dataIndex : 'first',renderer:datarender}, {header : '第二列',dataIndex : 'second'}, {header : '第三列',dataIndex : 'third'}, {header : '第四列',dataIndex : 'four',format:'Y-m-d H:i:s',width:120} ];var store = new Ext.data.Store({proxy : {//擷取資料的方式type : 'ajax',url : 'grid_StoreMsg',reader : {//解析資料方式type : 'json',root : 'model'//指定返回JSON中key}},fields : [ {name : 'first'}, {name : 'second'}, {name : 'third'}, {name : 'four'} ]});store.load();var grid = new Ext.grid.GridPanel({renderTo : 'grid',columns : columns,store : store});});這裡使用Struts2對請求進行攔截,看Struts,xml
這裡需要返回值類型定義為JSON,所有package要整合自json-default。下面看具體的類。
為了方便資料轉送,將表格中的每一行看成一個對象。將他資訊封裝成一個javabean。
package model;public class Model {private String first;private String second;private String third;private String four;public Model(){}public Model(String first,String second,String third,String four){this.first = first;this.second = second;this.third = third;this.four = four;}public String getFirst() {return first;}public void setFirst(String first) {this.first = first;}public String getSecond() {return second;}public void setSecond(String second) {this.second = second;}public String getThird() {return third;}public void setThird(String third) {this.third = third;}public String getFour() {return four;}public void setFour(String four) {this.four = four;}}這裡定義一個方法直接返回這個Model類的對象,在實際生產中需要經過處理後得到對象。
package service;import model.Model;public class Service {public Model modelMsg(){Model model = new Model();model.setFirst("第一行");model.setSecond("第二行");model.setThird("第三行");model.setFour("20150205 14:32:46");return model;}}下面看一個Action類
package action;import service.Service;import model.Model;import com.opensymphony.xwork2.ActionSupport;public class GridAction extends ActionSupport {private Model model;private Service service = new Service();public Model getModel() {return model;}public void setModel(Model model) {this.model = model;}public String StoreMsg(){model = service.modelMsg();return SUCCESS;}}應為Struts定義的類型為JSON,而且在設定檔中沒有限制返回的欄位,所有經過Action處理後將會把所有的屬性封裝成一個JSON對象返回。因此在Store的reader中需要指定root屬性,方便解析。下面看一下firebug的顯示,以及運行效果。
如果返回的資料是多條的話可以在Action中定義一個ArrayList對象,這個對象中儲存的對象是需要返回的列的資訊。同時將reader中的root值改為這個ArrayList對象名稱即可。