---
title: "使用ext2的form提交表单（非AJAX方式）"
author: "beckrabbit"
date: "2007-10-16T22:25:09Z"
tags: []
slug: "ext2-form-ajax"
draft: false
lastmod: "2007-10-16T22:25:09Z"
id: 132686
url: "https://beckrabbit.iteye.com/blog/132686"
---

虽然ext自带的ajax支持还是不错的，可我还是习惯用DWR来做AJAX，因为对于J2ee开发来说这无疑是最好的选择

ext的form提供了两种表单方式，一是ajax的另一种是非ajax的，前者要求服务端返回的数据一定要是json格式，这让我很不习惯，还是dwr的好...在这里用登录窗口的例子，说一下后者。

后台就不多说了，至少需要一个验证用户的service方法 boolean userlogin(String username,String password);

或者返回String类型给用户更详细的登录失败信息。

如果用Struts来做界面控制的话需要一个userlogin.do 获取form提交的username和password，调用service层的userlogin方法决定跳转的页面。

首先添加一个FORM，直接在JS里面写下面代码就可以生成一个FORM ，无需任何页面代码。

js 代码

01. var simple = new Ext.form.FormPanel({
02. labelWidth: 75, // label settings here cascade unless overridden
03. url:'../userlogin.do',
04. method:'POST',
05. frame:true,
06. title: '登录窗口',
07. bodyStyle:'padding:5px 5px 0',
08. width: 300,
09. defaults: {width: 200},
10. defaultType: 'textfield',
11. //实现非AJAX提交表单一定要加下面的两行！
12. onSubmit: Ext.emptyFn,
13. submit: function() {
14. //有疑问的地方
15. this.getEl().dom.action='../userlogin.do';
16. this.getEl().dom.submit();
17. },
18. items: [{
19. fieldLabel: '用户名',
20. id: 'username',
21. allowBlank:false,
22. width:150
23. },{
24. fieldLabel: '密码',
25. id: 'password',
26. allowBlank:false,
27. width:150,
28. inputType:'password'
29. }
30. ],
31. buttons: [{
32. text: '登录',
33. type:'button',
34. id:'login',
35. handler: login
36. },{
37. text: '重置',
38. type:'reset',
39. id:'clear',
40. handler: reset
41. }
42. ]
43. });

这个就是ext2.0的form模型，使用了新的Ext.form.FormPanel做form，需要注意的是使用非ajax也就是传统方式的话一定要在form的属性加入这两行：

js 代码

1. onSubmit: Ext.emptyFn,
2. submit: function() {
3. this.getEl().dom.submit();
4. },

这是API里指定的用法，可是我这么做确不能正确提交FORM ，仔细检查后发现ext生成的html代码中这个form没有action项，只有id和method，通过form的url属性和在submit参数中直接添加url或者action貌似都不起作用。

所以我在这里又加了一句：this.getEl().dom.action='../userlogin.do';在提交表单的时候 直接把FORM的action属性设置到html里

这样就可以正确提交了，但不知道是不是最好的方法。

button的handler属性值确定了两个按钮按下时触发的方法。

js 代码

1. function reset(){
2. simple.form.reset();
3. }
4. function login(item){
5. simple.form.submit();
6. }

当然也可以在login中使用dwr进行ajax形式的表单提交。