对web应用效率提升的一些经验及疑问

1. 对dom节点的使用:

    尽量避免使用dom对象,大家都知道对dom树的遍历非常耗费资源,因此如果需要重复使用时,将dom对象存在一个js的变量中,然后对这个变量进行使用,避免每次使用dom节点时对dom树的遍历,切记,在使用完对dom对象引用的变量后要将其置为null,否则你会发现内存的占用率有增无减,直到你关闭了浏览器为止。

2. 对eval函数的使用:

     在使用eval函数时,会增加了对eval函数中代码解析的过程,而这个解析的过程是非常耗费资源的,因此,尽量避免使用eval函数,如果非用不可,也要尽可能的减少eval解析的代码量,将需要执行的代码提取到一个方法内,eval只解析这个函数名来提高eval的效率,可以通过以下的示例进行比较:

    方法一:

eval("for(var i = 0; i < 10000000; i ++) { var str = 'test' + i }");

      方法二:

var test = function() { 
    for(var i = 0; i < 10000000; i ++) {
        var str = 'test' + i; 
    } 
} 
var testFun = eval('test'); 
testFun(); 

3. try-catch的使用:

    尽量把try-catch语句放在循环外边。

4. 全局变量的使用:

     全局变量的生命周期贯穿整个脚本的生命周期,而本地变量的存在范围随着本地命名空间的销毁而消失。当在函数或其它地方引用一个全局变量时,脚本引擎需要搜索整个全局命名空间。

5. 压缩合并js和css文件:

     这方面的优化估计很多人都做过,现在有好多JS和CSS压缩和混淆的工具,如yahoo的yui-compressor.jar,在页面完全使用Ext等js框架开发时压缩和混淆JS对效率提升尤其明显。

6. 异步请求中GET与POST的选择:

     大家都知道用GET方式来发送HTTP请求效率要远远高于POST请求,但是出于安全的考虑,这里需要慎重选择请求方式,可以参考我的另外一篇文章。

 

——————————————————————————————– 

 

另外,还有一些开发过程中的细节也会对效率提升起到一定得作用:

1. 不要使用with语句

2. str += “aaa”; str += “bbb”; 效率大于 str = “aaa” + “bbb”;

3. 原生的态的写法效率大于函数,如:

    a > b   a : b; 效率大于 Math.max(a, b);

    array[array.length] = obj; 效率大于 array.push(obj);

4. 对数组进行遍历时,先把数组的长度保存在变量中

for(var i = 0, len = array.length; i < len; i ++) { 
    // 遍历数组 
}

5. innerHTML方法效率大于createElement()/appendChild()方法

6. 尽量减少图片链接个数,减少对带宽的耗费

 

——————————————————————————————–

 

目前还在对以下几方面的优化进行分析和研究,都是本机测试,基本可以忽略网络问题,希望高人可以进行指点:

1. ajax以POST方式发送异步请求时的性能优化

    现状:用HTTPWATCH检测时,SEND时间过长,有时竟然会超过0.8秒,传输量并不大,   

    请求信息:

    Content-Type : application/x-www-form-urlencoded;charset=UTF-8

    Content-Length : 133 (10个字符串参数)

2. 在接收response的content时的性能优化

    现状:用HTTPWATCH监测时,RECEIVE时间过长

    response信息:

    HTTP/1.1 200 OK

    Server : Apache-Coyote/1.1

    Content-Type : text/plain;charset=UTF-8

    Content-Length : 4147

3. 在多个请求之间会有延时,如第一个请求完成之后会有零点几秒的延时才会进行下一个请求,那么这个延时的时间可以进行优化吗?这个延时的时间到底是在做什么呢?执行javascript代码?还是请求的等待队列?

希望高人可以指点,先行谢过!

 

Extjs.GridPanel显示多行工具栏(tbar)

js文件。。  

Ext.onReady(function() {

	//初始化数据
			var proData = {
				records : [{
							proName : "cocobra 居家内衣系列"
						}, {
							proName : "cocobra 休闲内衣系列"
						}]
			}
			
		
			var proCreate = new Ext.data.Record.create([{
						name : "proName",
						mapping : "proName",
						type : "string"
					}]);

			var fields = [{
						name : 'proName',
						mapping : 'proName'
					}];

			
			var proStore = new Ext.data.JsonStore({
						fields : fields,
						data : proData,
						root : 'records'
					});

			var rowNum = new Ext.grid.RowNumberer();  //添加行号
			var projectColumn = new Ext.grid.ColumnModel([rowNum, {
						header : "项目名称",
						width : 160,
						dataIndex : "proName",
						id : "proName",
						sortable : true  //设置排序
					}]);

			//第二個工具欄
			var tbar2 = new Ext.Toolbar({
						renderTo : Ext.grid.GridPanel.tbar,// 其中grid是上边创建的grid容器
						items : [{
									text : '添加',
									iconCls:'addBtn'
								}, {
									xtype : "tbseparator"
								}, {
									text : "删除",
									iconCls : "deleteBtn"   //图片样式, 需要自己寫css樣式,引入手寫的css,如果用自带会因为浏览器不兼容而不显示图片
								}, {
									xtype : "tbseparator"
								}, {
									text : "删除全部",
									iconCls:'deleteBtn'
								}, {
									xtype : "tbseparator"
								}, {
									text : '保存',
									iconCls:'saveBtn'
								}]

					});

	var tbar3 = new Ext.Toolbar({
				renderTo: Ext.grid.GridPanel.tbar,
				items:[new Ext.form.TextField({
					fieldLabel:"测试"
				//	width:100
					//height:30
				})]
			})



			var projectGrid = new Ext.grid.GridPanel({
						renderTo : "hello",
						title : "项目管理",
						widht : 180,
						height : 200,
						cm : projectColumn,
						store : proStore,
						autoScroll : true, // 内容溢出时产生滚动条
						tbar : [new Ext.form.ComboBox({
									store : ["喜羊羊与灰太狼", "cocobra"],    //給ComboBox添加數據
									emptyText : '请选择供应商',
									id : "provider",
									name : "provider",
									editable : false   //是否允許輸入

								})],
						listeners : {     //將第二個bar渲染到tbar裏面,通过listeners事件
							'render' : function() {
								tbar2.render(this.tbar);
          tbar3.render(this.tbar);
							}
						}
					});
		});

— 在按钮旁边添加图片的css样式

.deleteBtn {
   background-image: url(../images/default/dd/drop-no.gif) !important;
   margin-right:5px;
   background-repeat: no-repeat;
}

.addBtn {
   background-image: url(../images/default/dd/drop-add.gif) !important;
   margin-right:5px;
   background-repeat: no-repeat;
}

.saveBtn {
   background-image: url(../images/default/dd/drop-yes.gif) !important;
   margin-right:5px;
   background-repeat: no-repeat;
}

sencha-touch入门一环境配置

首先要配置开发环境。

这个很简单,只要到官方网站下载sencha-touch压缩包即可 http://www.sencha.com/products/touch/

开发工具随便一个编辑器,记事本也可以的。

 

本人用的是myEclipse+tomcat,sencha-touch用的是1.01版本

(使用myEclipse+tomcat我为了以后例子可以跟后台交互)

其实可以直接浏览本地静态html文件的。

 

 

1,编写messageBox.html文件:

 

<!doctype html>
<html>
  <head>
  	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">	
    <title>messageBox.html</title>
	<link rel="stylesheet" href="../../ext/resources/css/sencha-touch.css" type="text/css">
    <script type="text/javascript" src="../../ext/sencha-touch.js"></script>
    <script type="text/javascript" src="messageBox.js"></script>
  </head>
  
  <body>
    
  </body>
</html>

 
 如果你以前用过Extjs,那么这段代码你很容易明白。

1,引入sencha-touch.css样式文件。

2,引入sencha-touch.js核心库文件。

3,messageBox.js是例子用的文件。

 

2,编写messageBox.js文件:

 

Ext.setup({
    icon: '../icon.png',
    tabletStartupScreen: '../tablet_startup.png',
    phoneStartupScreen: '../phone_startup.png',
    glossOnIcon: false,
    onReady: function() {
    	Ext.Msg.alert('提示', '第一个SenchaTouch程序!');
    }
});

 

现在我们只关心onReady函数里面的代码,其他可以copy。

如果你以前做过Extjs那么看API难不到你。你可以在onReady中使用其他组件进行测试的。

 

3,运行效果:

本人使用的是Opera的手机模拟器(支持HTML5),google浏览器也可以的。

在浏览器输入http://localhost:8080/SenchaTouchTest/myExample/messageBox/messageBox.html

当然你可以直接打开html进行浏览而不必要部署到服务器(我为了以后例子可以跟后台交互)

 

  • 大小: 31.3 KB
  • 大小: 29.5 KB

EXT学习资料

之前用过YUI 但是害怕CSS 知道EXT不需要写太多的CSS,哈哈就打算学习下EXT,后来由于忙也忘了学习。

可能以后会很少使用EXT了。所以把之前的学习资料发出来分享下,方便以后学习的人使用。其实最好的学习方式是去官方网站看列子,英文不好的可以看下我这个学习的word,也是别人发给我的。永远记得一句话 分享快乐。

jspjava分页标签

java

package org.whvcse.common;

import java.io.Serializable;
/**
 * @desc 分页容器类
 * @author mengdejun 
 */
public class Page implements Serializable 
{
	private static final long serialVersionUID = 1L;
	private int allPage = 0;//总页数
	private int allRecords = 0;//总记录
	private int currentPage = 1;//当前页
	private String link = null;//链接信息
	private int perRecords = 5;//显示条数

	public int getAllPage() {
		return allPage;
	}

	public int getAllRecords() {
		return allRecords;
	}

	public int getCurrentPage() {
		return currentPage;
	}
	/**
     * 
     * @return 容器索引结束坐标
     */
	public int getEndIndex() {
		return ((this.currentPage - 1) * this.perRecords + this.perRecords > this.allRecords)   this.allRecords
				: (this.currentPage - 1) * this.perRecords + this.perRecords;
	}

	public String getLink() {
		return link;
	}

	public int getPerRecords() {
		return perRecords;
	}
    /**
     * 
     * @return 容器索引开始坐标
     */
	public int getStartIndex() {
		return (this.currentPage - 1) * this.perRecords;
	}

	public boolean hasNext() {
		return this.currentPage < this.allPage;
	}

	public boolean hasPrevious() {
		return this.currentPage > 1;
	}

	public void setAllPage(int allPage) {
		this.allPage = (allPage % this.perRecords == 0)   (allPage / this.perRecords)
				: (allPage / this.perRecords + 1);
	}

	public void setAllRecords(int allRecords) {
		this.allRecords = allRecords;
	}

	public void setCurrentPage(int currentPage) {
		if (currentPage < 1)
			this.currentPage = 1;
		else if (currentPage > this.allPage)
			this.currentPage = this.allPage;
		else
			this.currentPage = currentPage;
	}

	public void setCurrentPage(String currentPage) {
		if (null == currentPage || currentPage.equals(""))
			currentPage = "1";
		try {
			this.setCurrentPage(Integer.parseInt(currentPage));
		} catch (NumberFormatException e) {
			this.currentPage = 1;
		}
	}

	public void setLink(String link) {
		this.link = link;
	}

	public void setPerRecords(int perRecords) {
		this.perRecords = perRecords;
	}

	public void setPerRecords(String perRecords) {
		try {
			this.perRecords = Integer.parseInt(perRecords);
		} catch (NumberFormatException e) {
			this.perRecords = 5;
		}
	}
}

 

package org.whvcse.ext;
import java.io.Serializable;
import javax.servlet.ServletRequest;
import org.whvcse.common.Page;
/**
 * @desc 标签生成器接口 拓展生成器需实现该接口并返回链接字符串 
 * @author mengdejun
 */
public interface LinkHandler extends Serializable 
{
	/**
	 * 
	 * @param page 分页类信息
	 * @param request httpServletRequest对象封装
	 * @param format 链接信息格式化
	 * @param param 当前分页标签变量
	 * @return 链接字符串
	 * @throws NullPointerException
	 */
	public String parse(Page page,ServletRequest request,String format,String param) throws NullPointerException;
}

 

package org.whvcse.ext.link;

import javax.servlet.ServletRequest;

import org.whvcse.common.Page;
import org.whvcse.ext.LinkHandler;
/**
 * @desc 默认链接生成器,该类需自己扩展以实现自己的样式,需实现LinkHandler接口,自定义时候请在标签cls属性填入类的全名
 * @author mengdejun
 */
public class GeneralLinkHandler implements LinkHandler
{
	private static final long serialVersionUID = 1L;
	public String parse(Page page,ServletRequest request,String format,String param) throws NullPointerException 
	{
		String returnStr="共"+page.getAllPage()+"页,第"+page.getCurrentPage()+"页&nbsp;";
		for(int i=1;i<=page.getAllPage();i++)
		{
			returnStr+="<a href=index.jsp "+param+"="+i+">"+i+"</a>&nbsp;";
		}
		return returnStr;
	}
}

 

package org.whvcse.page;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import org.whvcse.ext.LinkHandler;
public class TagLink extends TagSupport 
{
	private static final long serialVersionUID = 1L;
	private TagPage page=null;//父容器
	private String format="共{allPage},第{currentPage}";//链接格式,可自定义
	private LinkHandler handler=null;//链接处理类
	private String var=null;//返回信息
	private String cls="org.whvcse.ext.link.GeneralLinkHandler";//默认链接类
	@SuppressWarnings({ "static-access", "unchecked" })
	@Override
	public int doEndTag() throws JspException
	{
		//获取父容器标签对象
		this.page=(TagPage) this.findAncestorWithClass(this,TagPage.class);
		JspWriter out=this.pageContext.getOut();
		try 
		{
			Class c = Class.forName(this.cls);//插件设置,加载自定义插件类
			this.handler=(LinkHandler) c.newInstance();
			String temp=this.handler.parse(this.page.getPage(),pageContext.getRequest(),this.format,this.page.getParam());
			if(null==this.var)
			{
				out.println(temp);
			}
			else
			{
				this.pageContext.setAttribute(this.var,temp,this.page.getScope(this.page.getScope()));
			}
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		}
		catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return EVAL_PAGE;
	}
	public String getFormat() 
	{
		return format;
	}
	public void setFormat(String format) {
		this.format = format;
	}
	public String getCls() {
		return cls;
	}
	public void setCls(String cls) {
		this.cls = cls;
	}
	public String getVar() {
		return var;
	}
	public void setVar(String var) {
		this.var = var;
	}
	
	
}

 

package org.whvcse.page;
import java.util.List;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.whvcse.common.Page;
public class TagPage extends BodyTagSupport 
{
	private static final long serialVersionUID = 1L;
	private String id=null;//数据源ID
	private String target=null;//目标源,处理后的链表
	private String scope=null;//变量作用域
	private String param=null;//当前页标签变量
	@SuppressWarnings("unchecked")
	private List list=null;
	private Page page=null;//分页类
	private String rows="5";//显示行数
	public TagPage()
	{
		this.scope="request";
		this.param="page";
		this.target="pageData";
	}
	@Override
	public int doEndTag() throws JspException 
	{
		super.pageContext.removeAttribute(this.id, this.getScope(this.scope));
		return EVAL_PAGE;
	}
	@SuppressWarnings("unchecked")
	@Override
	public int doStartTag() throws JspException 
	{
		this.list=(List) super.pageContext.getAttribute(this.id,this.getScope(this.scope));
		this.page=new Page();
		this.page.setAllRecords(this.list.size());
		this.page.setPerRecords(this.rows);
		this.page.setAllPage(this.list.size());
		String start=super.pageContext.getRequest().getParameter(this.param);
		this.page.setCurrentPage(start);
		this.list=this.list.subList(this.page.getStartIndex(),this.page.getEndIndex());
		super.pageContext.setAttribute(this.target, this.list, this.getScope(this.scope));
		return EVAL_BODY_INCLUDE;
	}

	public String getId() 
	{
		return id;
	}
	public void setId(String id) 
	{
		this.id = id;
	}
	public String getTarget() 
	{
		return target;
	}
	public void setTarget(String target) 
	{
		this.target = target;
	}
	public String getScope() {
		return scope;
	}
	public void setScope(String scope) {
		this.scope = scope;
	}
	public String getParam() {
		return param;
	}
	public void setParam(String param) {
		this.param = param;
	}
	@SuppressWarnings("static-access")
	public int getScope(String scope)
	{
		if(scope.equals("request")||scope.equals("REQUEST")||scope.equals("r"))return super.pageContext.REQUEST_SCOPE;
		if(scope.equals("session")||scope.equals("SESSION")||scope.equals("s"))return super.pageContext.SESSION_SCOPE;
		if(scope.equals("application")||scope.equals("APPLICATION")||scope.equals("a"))return super.pageContext.APPLICATION_SCOPE;
		if(scope.equals("page")||scope.equals("PAGE")||scope.equals("p"))return super.pageContext.PAGE_SCOPE;
		return super.pageContext.REQUEST_SCOPE;
	}
	public String getRows() 
	{
		return rows;
	}
	public void setRows(String rows) 
	{
		this.rows = rows;
	}
	public Page getPage() 
	{
		return page;
	}	
	
}

 

< xml version="1.0" encoding="UTF-8" >
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
                        "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
 <tlib-version>1.3</tlib-version>
 <jsp-version>1.2</jsp-version>
 <short-name>whvcse</short-name>
 <uri>http://mengdejun.iteye.com</uri>
 <tag>
  <name>page</name>
  <tag-class>org.whvcse.page.TagPage</tag-class>
  <body-content>JSP</body-content>
  <description/>
  <attribute>
   <name>scope</name>
   <rtexprvalue>true</rtexprvalue>
   <description>
         分页类
         </description>
  </attribute>
   <attribute>
   <name>param</name>
    <required>false</required>
   <rtexprvalue>true</rtexprvalue>
   <description>
           页码
         </description>
  </attribute>
   <attribute>
   <name>rows</name>
    <required>false</required>
   <rtexprvalue>true</rtexprvalue>
   <description>
          显示行数
         </description>
  </attribute>
  <attribute>
   <name>id</name>
   <required>true</required>
   <rtexprvalue>true</rtexprvalue>
   <description>
          变量列表
         </description>
  </attribute>
  <attribute>
   <name>target</name>
   <required>true</required>
   <rtexprvalue>true</rtexprvalue>
   <description>
       别名
         </description>
  </attribute>
 </tag>
 <tag>
  <name>pageLink</name>
  <tag-class>org.whvcse.page.TagLink</tag-class>
  <body-content>empty</body-content>
  <description/>
  <attribute>
   <name>format</name>
   <required>false</required>
   <rtexprvalue>true</rtexprvalue>
   <description>
          链接信息
         </description>
  </attribute>
  <attribute>
   <name>cls</name>
   <required>false</required>
   <rtexprvalue>true</rtexprvalue>
   <description>
           扩展信息,实现LinkHandler接口
         </description>
  </attribute>
  <attribute>
   <name>var</name>
   <required>false</required>
   <rtexprvalue>true</rtexprvalue>
   <description>
           该属性将不输出分页信息,将信息赋给var变量
         </description>
  </attribute>
 </tag>
</taglib>

 

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@ taglib prefix="whvcse" uri="http://mengdejun.iteye.com"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>分页标签实例</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  <%
  	List a=new ArrayList();
  for(int i=1;i<=50;i++)
  {
		a.add(i);
 		request.setAttribute("list",a);
  }
   %>
  <body>
   <whvcse:page id="list" target="olist" scope='request' rows='10'><!-- 分类标签 -->
   <%
   			List o=(List)request.getAttribute("olist");
   			for(int i=0;i<o.size();i++)
   			{
   				out.print(o.get(i)+"<br/>");
   			}
   		 %>
   		<whvcse:pageLink/>
   </whvcse:page>
  </body>
</html>

Ext.ux.UploadDialog.DialogExt上传

今天做项目做了个上传的功能,不过遇到好多问题,先在这做个笔记。。。。

先引入

    <link rel="stylesheet" type="text/css" href="<%=path %>/css/ext-all.css" />
	<!-- GC -->
	<!-- LIBS -->
	<script type="text/javascript" src="<%=path %>/js/ext-base.js"></script>
	<!-- ENDLIBS -->
	<script type="text/javascript" src="<%=path %>/js/ext-all.js"></script>
	<script type="text/javascript" src="<%=path %>/js/ext-lang-zh_CN.js"></script>
		
	<script type="text/javascript" src="<%=path %>/js/UploadDialog/Ext.ux.UploadDialog.js"></script>
		
	<script type="text/javascript" src="<%=path %>/js/UploadDialog/Ext.ux.UploadDialog.packed.js"></script>

Ext代码:

    /**
     * 文件上传
     */
    function insertImages() 
	{ 
		var editId=Ext.getCmp('queId').getValue();
		//alert('../files.do method=addFile&type=ntc&tmpId='+useId+'&isupdate='+isupdate+'&editId='+editId);
    	dialog = new Ext.ux.UploadDialog.Dialog({ 
	          title: '文件上传',  
	          url:paths+'/files.do method=addFile&type=que&tmpId='+useId+'&isupdate='+isupdate+'&editId='+editId,  
	          width : 450, 
	          height : 300, 
	          minWidth : 450, 
	          minHeight : 300, 
	          draggable : true, 
	          resizable : true, 
	          //autoCreate: true,    
	          constraintoviewport: true,  
	          permitted_extensions:['ZIP','zip','DOC','doc','XLS','xls','TXT','txt','RAR','rar','JPG','jpg','GIF','gif','PNG','png'],    
	          modal: true, 
	          //post_var_name: 'mms', 
	          post_var_name: 'upload', 
	          reset_on_hide: false,  
	          allow_close_on_upload: true,   //关闭上传窗口是否仍然上传文件 
	          upload_autostart: true   
	    }); 
    	dialog.show();//'show-button' 
    	dialog.on('uploadsuccess', onUploadSuccess); 
	} 


	function onUploadSuccess(dialog, filename, resp_data, record){   
	  				var queId='';
					if(isupdate==1)
						queId=useId;
					if(isupdate==2)
						queId=Ext.getCmp('queId').getValue();
					fileDs.load({
						params: {
							findId: queId,
							type:'que',
							isupdate:isupdate
								}
					});
	}

Ext.ux.UploadDialog中的其它事件函数[转载自http://wayfoon.iteye.com/blog/432541]

    * filetest – fires before file is added into the queue, parameters:

      dialog – reference to dialog

      filename – file name

      If handler returns false then file will not be queued.

    * fileadd – fires when file is added into the queue, parameters:

      dialog – reference to dialog

      filename – file name

    * fileremove – fires when file is removed from the queue, parameters:

      dialog – reference to dialog

      filename – file name

      record – file record

    * resetqueue – fires when upload queue is resetted, parameters:

      dialog – reference to dialog

    * beforefileuploadstart – fires when file as about to start uploading:

      dialog – reference to dialog

      filename – uploaded file name

      record – file record

      If handler returns false then file upload will be canceled.

    * fileuploadstart – fires when file has started uploading:

      dialog – reference to dialog

      filename – uploaded file name

      record – file record

    * uploadsuccess – fires when file is successfuly uploaded, parameters:

      dialog – reference to dialog

      filename – uploaded file name

      data – js-object builded from json-data returned from upload handler response.

      record – file record

    * uploaderror – fires when file upload error occured, parameters:

      dialog – reference to dialog

      filename – uploaded file name

      data – js-object builded from json-data returned from upload handler response.

      record – file record

    * uploadfailed – fires when file upload failed, parameters:

      dialog – reference to dialog

      filename – failed file name

      record – file record

    * uploadcanceled – fires when file upload canceled, parameters:

      dialog – reference to dialog

      filename – failed file name

      record – file record

    * uploadstart – fires when upload process starts, parameters:

      dialog – reference to dialog

    * uploadstop – fires when upload process stops, parameters:

      dialog – reference to dialog

    * uploadcomplete – fires when upload process complete (no files to upload left), parameters:

      dialog – reference to dialog

extjs表格增加竖线

Extjs 默认中的表格是没有竖线的,我们只需要加入以下css,就可以显示出竖线了

 <style>
    /* Override standard grid styles (add colour to vertical grid lines) */  
.x-grid3-col {  
    border-left:  1px solid #EEEEEE;  
    border-right: 0px solid #D2D2D2;  
}  
  
/* Also remove padding from table data (to compensate for added grid lines) */  
.x-grid3-row td, .x-grid3-summary-row td {  
    padding-left: 0px;  
    padding-right: 0px;  
}
    </style>

 

如下所示:

 

 

  • 大小: 32.3 KB

extjs的grid控件如何根据值来设置某行的背景颜色

根据不同的值来设置grid的背景颜色

在viewConfig里面配置getRowClass就行了,例:

先自定义一个CSS:

<style type=”text/css”>

.my_row_Red table{ background:Red}

</style>

然后在GridPanel里这样写:

var QueryGrid=new Ext.grid.GridPanel({
            frame:true,
            renderTo:document.getElementById("QueryGrid"),
            enableColumnHide:false,
            columns:[
                {header:'姓名',sortable:true,dataIndex:'Name'},
                {header:'性别',dataIndex:'Sex'},
                {header:'年龄',dataIndex:'Age'}
            ],
            store:JQueryStore,
            loadMask: true,
            viewConfig:{forceFit:true,sortAscText:'正序',sortDescText:'降序',getRowClass : function(record,rowIndex,rowParams,store){ 
                            if(record.data.Sex=="1"){
                                return 'my_row_Red';
                            }                        }
            }
})

extajax和grid简单实践

<%@ page language=”java” contentType=”text/html; charset=GB18030″

    pageEncoding=”GB18030″%>

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>

<html>

<head>

<link rel=”stylesheet” type=”text/css” href=”<%=request.getContextPath() %>/js/resources/css/ext-all.css” />

<script type=”text/javascript” src=”<%=request.getContextPath() %>/js/adapter/ext/ext-base.js”></script>

<script type=”text/javascript” src=”<%=request.getContextPath() %>/js/ext-all.js”></script>

<script type=”text/javascript” src=”<%=request.getContextPath() %>/js/json.js”></script>

<meta http-equiv=”Content-Type” content=”text/html; charset=GB18030″>

<title>Insert title here</title>

<script type=”text/javascript”>

Ext.onReady(function(){

var my={};

my.name=”yk”;

my.age=”23″;

Ext.Ajax.request({

url:”http://localhost:8080/test/ajaxServlet”,

params:JSON.stringify(my),

success:function(response){

test(response);

}

});

function test(response)

{

var text=response.responseText;

alert(text);

var data=Ext.util.JSON.decode(text);

alert(data.name);

}

var data=[

{id:0,name:”yk”,age:”22″},

{id:1,name:”yk1″,age:”23″},

{id:2,age:”24″,name:”yk2″},

{name:”yk3″,age:”25″},

{id:4,name:”yk4″,age:”26″},

{id:5,name:”yk5″,age:”27″}

];

var data1=[

[1,”yk”,23],[2,26],[3,”yk3″,28]

];

var recordType=new Ext.data.Record.create([{name:”id”,mapping:”id”},{name:”name”,mapping:”name”},{name:”age”,mapping:”age”}]);

var jsonType={id:”id”};

var reader=new Ext.data.JsonReader(jsonType,recordType);

//var store=new Ext.data.SimpleStore({data:data1,fields:[“id”,”name”,”age”]});

var store=new Ext.data.JsonStore({data:data,fields:[“id”,”name”,”age”]});

var cms=[

{header:”id”,dataIndex:”id”,width:40},

{header:”name”,dataIndex:”name”,width:50},

{header:”age”,dataIndex:”age”,width:110}

];

var grid=new Ext.grid.GridPanel({

store:store,

columns:cms,

title:”测试数据表格”,

height:200,

width:200,

});

grid.render(“grid”);

})

</script>

</head>

<body>

<div id=”grid”></div>

</body>

</html>

EXT核心API详解(五)-Ext.EventManager/EventObject/CompositeElement/CompositeElementLite

Ext.EventManager
事件管理者中的大部分方法都在Ext中有定义,主要用于事件管理

addListener( String/HTMLElement el, String eventName, Function handler,
on( String/HTMLElement el, String eventName, Function handler, [Object scope], [Object options] ) : void
onDocumentReady( Function fn, [Object scope], [boolean options] ) : void
removeListener( String/HTMLElement el, String eventName, Function fn ) :
un( String/HTMLElement el, String eventName, Function fn ) : Boolean
参见Ext

onWindowResize( Function fn, Object scope, boolean options ) : void
窗口大小变更时触发

onTextResize( Function fn, Object scope, boolean options ) : void
活动文本尺寸变更时触发

Ext.EventObject
这两个类都定义在EventManager.js中,分开是为了逻辑上更清晰吧,这个类主要用于描述事件本身,一般用做事件处理方法的参数
另外这个害定义了一些键值常量,比ascii码好记

function handleClick(e){ // 这儿的e就是一个EventObject对象
    e.preventDefault();
    var target = e.getTarget();
    …
 }
 var myDiv = Ext.get(“myDiv”);
 myDiv.on(“click”, handleClick);
 //or
 Ext.EventManager.on(“myDiv”, ‘click’, handleClick);
 Ext.EventManager.addListener(“myDiv”, ‘click’, handleClick);

getCharCode() : Number
getKey() : Number
在非webkit|khtml类型网页中这两个方法是一样的,得到按键的值

getPageX() : Number
getPageY() : Number
getXY() : Array
得到事件坐标

getRelatedTarget() : HTMLElement
得到关联目标 我总是得到null

getTarget( [String selector], [Number/Mixed maxDepth], [Boolean returnEl] ) :
如果没有定义selector则直接返回target属性,如果定义了selector,则利用selector寻找祖先节点

getTime() : Number
得到事件发生的时间 

getWheelDelta() : Number
应该是个过时的方法,反正在ie和火狐下都不知道做什么用的,原意应该是得到鼠标的按键信息?

hasModifier() : Boolean
事件发生时是否同时按下了ctrl/alt/shift键之一?

preventDefault() : void
阻止浏览器的默认事件?

stopEvent() : void
preventDefault+stopPropagation

stopPropagation() : void
阻止事件冒泡

within( Mixed el, [Boolean related] ) : Boolean
如果事件的目标是el或者它的子节点将返回真

Ext.CompositeElement类
基础的复合元素类,为容器中每个元素创建一个Ext.Element对象
虽然不是继承自Ext.Element,但事实上它几乎支持Element类的所有方法
例:
var els = Ext.select(“#some-el div.some-class”, true);
els.setWidth(100);

add( String/Array els ) : CompositeElement
添加 css选择器els匹配的元素 或 元素组成的数组 到当前对象

clear() : void
清除所有元素

contains() : Boolean
应该是contains(Mixed el):Boolean,当前复合元素中是否含有el

each( Function fn, [Object scope] ) : CompositeElement
通过el,this,index参数为每个元素调用fn

fill( String/Array els ) : CompositeElement
clear()& add(els)

filter( String selector ) : CompositeElement
过滤

first() : Ext.Element
第一个元素

getCount() : Number
//元素的数量

indexOf() : Boolean
同contains一样应该有个Mixed参数

item( Number index ) : Ext.Element
第index个元素

last() : Ext.Element
最后一个元素

removeElement( Mixed el, [Boolean removeDom] ) : CompositeElement
删除el元素

replaceElement( Mixed el, Mixed replacement, [Boolean domReplace] ) : CompositeElement
替换

Ext.CompositeElementLite
由Ext.CompositeElement继承而来,重写了一些方法,但没看出与父类有什么不同
addElements /invoke /item /addListener /each /indexOf /replaceElement