使用extjs4.0实现动态列及分页

来源:互联网 发布:子域名的作用 编辑:程序博客网 时间:2024/06/06 03:40

    在做信息管理系统类项目时,用户有时需要实现表格的列头(列名字段)可以根据数据库返回的结果集不同而有不同的显示,包括字段名或者字段顺序。比如,同样是邮件列表,可以根据用户个人配置,显示“标题、发送时间、发送人”或者“发送时间、发送人、标题”又或者“标题、正文简介”等。这个时候,如何使用extjs自带的grid组件实现呢?

    首先,我们需要知道extjs的grid组件与后台程序之间传输数据一般使用json,而对于json这种形式,在struts2框架下,要实现不变列名(及列名使用硬编码配置,无法根据后台返回结果不同而有不同显示),比较简单,只要在action中定义相关类属性,在js中做相应的字段绑定即可。如果要实现动态列,就需要自己手动在action中将结果集(一般从数据库中查询得出)转化成json格式,并写入到response中,返回至客户端,交由extjs的grid组件进行渲染显示。

    下面贴出笔者的js代码和后台action代码,感兴趣的同学可以参考一二。

    1、js代码

     

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>动态生成表格</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"><link rel="stylesheet" type="text/css"href="ext4/resources/css/ext-all.css"><script type="text/javascript" src="ext4/bootstrap.js"></script><script type="text/javascript" src="ext4/ext-all.js"></script><script type="text/javascript" src="ext4/locale/ext-lang-zh_CN.js"></script><script type="text/javascript">Ext.onReady(function() {var json_f;Ext.Ajax.request({//store对象在创建时需要制定fields属性,因此使用ajax首先从后台获得列名url : 'json/testUser!testPage.action', //从action返回的response中读取数据,也可以从其他地方获取数据 method : 'POST',async : false,success : function(response) {//将返回的结果转换为json对象,注意extjs4中decode函数已经变成了:Ext.JSON.decodes = response.responseText;json_f = Ext.JSON.decode(response.responseText); //获得后台传递json }});var thePageSize = 5;//JSON数据源,此处创建了带有分页功能的store数据源var humresStore = Ext.create('Ext.data.Store', {pageSize : thePageSize,fields : json_f.fields,//根据上面的ajax从后台action动态获得proxy : {type : 'ajax',url : 'json/testUser!testPage.action',//获取数据的urlmethod : 'POST',reader : {type : 'json',root : 'data',totalProperty : 'totalRecord'//json数据,表示分页数据总数}},sorters : [ {property : 'id',direction : 'DESC'} ]});humresStore.load({params : {start : 0,limit : thePageSize}});//创建表格,可以加入更多的属性。Ext.create("Ext.grid.Panel", {title : '动态表格~~~~~~~~~~~',width : 400,height : 300,id : 'configGrid',name : 'configGrid',columns : [], //注意此行代码,至关重要displayInfo : true,emptyMsg : "没有数据显示",renderTo : 'grid',//渲染到页面forceFit : true,dockedItems : [ {xtype : 'pagingtoolbar',store : humresStore,dock : 'bottom',displayInfo : true,//displayMsg: '显示第 {0} 条到 {1} 条记录 / 共 {2} 条',emptyMsg : "没有记录!"} ]});//通过ajax获取表头以及表格数据Ext.Ajax.request({url : 'json/testUser!testPage.action', //从json文件中读取数据,也可以从其他地方获取数据 method : 'POST',success : function(response) {//将返回的结果转换为json对象,注意extjs4中decode函数已经变成了:Ext.JSON.decodevar json = Ext.JSON.decode(response.responseText); //获得后台传递json//根据store和column构造表格Ext.getCmp("configGrid").reconfigure(humresStore,json.columns);}});})</script></head><body><!-- 将表格渲染在此处 --><div id="grid"></div></body></html>
      2、action代码

      

package com.struts;import java.io.IOException;import javax.servlet.http.HttpServletResponse;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionSupport;public class testUser extends ActionSupport {/** *  */private static final long serialVersionUID = 1L;public String execute() throws Exception {return SUCCESS;}public void testPage() throws Exception {System.out.print("enter testPage");String start = (ServletActionContext.getRequest().getParameter("start") == null) ? "0": ServletActionContext.getRequest().getParameter("start");String gridJson;if (start.equals("0")) {gridJson = "{" + "'fields': [" + "{'name': 'id', 'type': 'int'},  "+ "{'name': 'name', 'type': 'string'},"+ "{'name': 'sex', 'type': 'string'},"+ "{'name': 'add', 'type': 'string'}" + "]," + "'data': ["+ "{'id': '1', 'name': 'AAA', 'sex': '男','add':'SSS'},"+ "{'id': '2', 'name': 'BBB', 'sex': '男','add':'SSS'},"+ "{'id': '3', 'name': 'CCC', 'sex': '男','add':'SSS'},"+ "{'id': '4', 'name': 'DDD', 'sex': '女','add':'是'},"+ "{'id': '5', 'name': 'EEE', 'sex': '男','add':'撒的发生'}"+ "]," + "'columns': ["+ "{'header': '编号', 'dataIndex': 'id'},"+ "{'header': '姓名', 'dataIndex': 'name'},"+ "{'header': '性别', 'dataIndex': 'sex'},"+ "{'header': '地址2', 'dataIndex': 'add'}" + "],"+ "'totalRecord':8,'success':true" + "}";} else {gridJson = "{" + "'fields': [" + "{'name': 'id', 'type': 'int'},  "+ "{'name': 'name', 'type': 'string'},"+ "{'name': 'sex', 'type': 'string'},"+ "{'name': 'add', 'type': 'string'}" + "]," + "'data': ["+ "{'id': '6', 'name': 'AAA', 'sex': '男','add':'SSS'},"+ "{'id': '7', 'name': 'BBB', 'sex': '男','add':'SSS'},"+ "{'id': '8', 'name': 'CCC', 'sex': '男','add':'SSS'},"+ "{'id': '9', 'name': 'DDD', 'sex': '女','add':'是'},"+ "{'id': '10', 'name': 'EEE', 'sex': '男','add':'撒的发生'}"+ "]," + "'columns': ["+ "{'header': '编号', 'dataIndex': 'id'},"+ "{'header': '姓名', 'dataIndex': 'name'},"+ "{'header': '性别', 'dataIndex': 'sex'},"+ "{'header': '地址2', 'dataIndex': 'add'}" + "],"+ "'totalRecord':8,'success':true" + "}";}HttpServletResponse response = ServletActionContext.getResponse();// 编制响应的格式response.setContentType("text/html;charset=UTF-8");try {response.getWriter().write(gridJson);} catch (IOException e) {e.printStackTrace();}}}
      3、json数据格式

      

{      'fields': [          {'name': 'id', 'type': 'int'},          {'name': 'name', 'type': 'string'},          {'name': 'sex', 'type': 'string'},        {'name': 'add', 'type': 'string'}    ],    'data': [          {'id': '1', 'name': 'AAA', 'sex': '男','add':'SSS'},          {'id': '2', 'name': 'BBB', 'sex': '男','add':'SSS'},           {'id': '3', 'name': 'CCC', 'sex': '男','add':'SSS'},           {'id': '4', 'name': 'DDD', 'sex': '女','add':'是'},           {'id': '5', 'name': 'EEE', 'sex': '男','add':'撒的发生'}     ],      'columns': [          {'header': '编号', 'dataIndex': 'id'},          {'header': '姓名', 'dataIndex': 'name'},          {'header': '性别', 'dataIndex': 'sex'},        {'header': '地址', 'dataIndex': 'add'}    ],"totalRecord"8,"success": true}
      4、struts.xml配置文件

      

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"><struts><constant name="struts.i18n.encoding" value="utf-8"></constant>        <package name="json" namespace="/json" extends="json-default">         <action name="testUser!*" class="com.struts.testUser" method="${1}"> <result type="json"></result></action>    </package></struts>    
     在action代码中修改返回json数据中的columns节实现列名不同显示,fields节数据为表格列的元数据,应与columns节数据对应,data为数据节,totalRecord为数据总条数,供分页控件使用。

原创粉丝点击