`
guoyiqi
  • 浏览: 964351 次
社区版块
存档分类
最新评论

FormPanel提交表单数据

阅读更多

今天研究FormPanel提交表单数据研究了半天.. 终于把表单提交成功了... 趁现在还记得问题,做一下总结:

 

1. 实用FormPanel如何提交表单:

    在Ext中FormPanel并中并不保存表单数据,其中的数据是由BasicForm保存,在提交表单的时候需要获取当前FormPanel中的BasicForm来进行提交. 

              获取FormPanel中的BasicForm对象代码如下:

   

Js代码 复制代码
  1. var pnlLogin = new Ext.FormPanel({   
  2.     //省略   
  3. });   
  4.   
  5. //获取BasicForm对象   
  6. pnlLogin.getForm();  
var pnlLogin = new Ext.FormPanel({
    //省略
});

//获取BasicForm对象
pnlLogin.getForm();

 

 在获取BasicForm对象后便可进行表单的提交操作...  此时需要查一下BasicForm 的API文档, 文档中说,需要调用submit();方法进行提交:

BasicForm submit方法API 写道
submit( Object options ) : BasicForm

Shortcut to do a submit action.

Parameters:

* options : Object
The options to pass to the action (see doAction for details)

Returns:

* BasicForm
this

 由API文档可以知道,submit方法实际上是调用了BasicForm的doAction()方法, 而doAction放法在API文档中的描述如下:

   

BasicForm doAction() API 写道
doAction( String/Object actionName, [Object options] ) : BasicForm

Performs a predefined action (Ext.form.Action.Submit or Ext.form.Action.Load) or a custom extension of Ext.form.Action to perform application-specific processing.

Parameters:

* actionName : String/Object
The name of the predefined action type, or instance of Ext.form.Action to perform.
* options : Object
(optional) The options to pass to the Ext.form.Action. All of the config options listed below are supported by both the submit and load actions unless otherwise noted (custom actions could also accept other config options):
o url : String

The url for the action (defaults to the form's url.)
o method : String

The form method to use (defaults to the form's method, or POST if not defined)
o params : String/Object

The params to pass (defaults to the form's baseParams, or none if not defined)
o headers : Object

Request headers to set for the action (defaults to the form's default headers)
o success : Function

The callback that will be invoked after a successful response. Note that this is HTTP success (the transaction was sent and received correctly), but the resulting response data can still contain data errors. The function is passed the following parameters:
+ form : Ext.form.BasicForm
The form that requested the action
+ action : Ext.form.Action
The Action class. The result property of this object may be examined to perform custom postprocessing.

o failure : Function

The callback that will be invoked after a failed transaction attempt. Note that this is HTTP failure, which means a non-successful HTTP code was returned from the server. The function is passed the following parameters:
+ form : Ext.form.BasicForm
The form that requested the action
+ action : Ext.form.Action
The Action class. If an Ajax error ocurred, the failure type will be in failureType. The result property of this object may be examined to perform custom postprocessing.

o scope : Object

The scope in which to call the callback functions (The this reference for the callback functions).
o clientValidation : Boolean

Submit Action only. Determines whether a Form's fields are validated in a final call to isValid prior to submission. Set to false to prevent this. If undefined, pre-submission field validation is performed.

Returns:

* BasicForm
this

 

这里actionName只能是 loadsubmit 当然提交的时候使用submit...

 

看了这么多的API文档, 其实关于表单提交操作并没有结束, 从doAction方法的描述中可以看出.. 这里实际上是调用了Ext.form.Action这个类, 而submit操作是调用了该类的子类Ext.form.Action.Submit...  绕了一大圈,终于把Ext中FormPanel是如何提交表单的原理搞的差不多了.. 那么下来就可以上代码了:

    

Java代码 复制代码
  1. var winLogin = new Ext.Window({   
  2.     title:'登录',   
  3.     renderTo:Ext.getBody(),   
  4.     width:350,   
  5.     bodyStyle:'padding:15px;',   
  6.     id:'login-win',   
  7.     buttonAlign:'center',   
  8.     modal:true,   
  9.     items:[{   
  10.         xtype:'form',   
  11.         defaultType:'textfield',   
  12.         bodyStyle : 'padding:5px',   
  13.         baseCls : 'x-plaints',   
  14.         url:'ajaxLogin.do',   
  15.         method:'POST',   
  16.         defaults:{   
  17.             anchor:'95%',   
  18.             allowBlank:false  
  19.         },   
  20.         items:[{   
  21.             id:'loginName',   
  22.             name:'loginName',   
  23.             fieldLabel:'用户名',   
  24.             emptyText:'请输入用户名',   
  25.             blankText:'用户名不能为空'  
  26.         },{   
  27.             id:'password',   
  28.             name:'password',   
  29.             fieldLabel:'密码',   
  30.             blankText:'密码不能为空'  
  31.         }]                             
  32.     }],   
  33.     buttons:[{   
  34.         text:'登录',   
  35.         handler:function(){   
  36.             //获取表单对象   
  37.             var loginForm = this.ownerCt.findByType('form')[0].getForm();   
  38.             alert(loginForm.getValues().loginName);   
  39.             loginForm.doAction('submit', {   
  40.                 url:'ajaxLogin.do',   
  41.                 method:'POST',                         
  42.                 waitMsg:'正在登陆...',   
  43.                 timeout:10000,//10秒超时,   
  44.                 <SPAN style="COLOR: #ff0000">params:loginForm.getValues(),//获取表单数据</SPAN>   
  45.                 success:function(form, action){   
  46.                     var isSuc = action.result.success;   
  47.                     if(isSuc) {   
  48.                         //提示用户登陆成功   
  49.                         Ext.Msg.alert('消息''登陆成功..');   
  50.                     }                                          
  51.                 },   
  52.                 failure:function(form, action){   
  53.                     alert('登陆失败');   
  54.                 }   
  55.             });   
  56.             this.ownerCt.close();   
  57.         }   
  58.     }, {   
  59.         text:'重置',   
  60.         handler:function(){   
  61.             alert('reset');   
  62.             this.ownerCt.findByType('form')[0].getForm().reset();   
  63.         }   
  64.     }]                         
  65. });   
  66. winLogin.show();  
var winLogin = new Ext.Window({
	title:'登录',
	renderTo:Ext.getBody(),
	width:350,
	bodyStyle:'padding:15px;',
	id:'login-win',
	buttonAlign:'center',
	modal:true,
	items:[{
		xtype:'form',
		defaultType:'textfield',
		bodyStyle : 'padding:5px',
		baseCls : 'x-plaints',
		url:'ajaxLogin.do',
		method:'POST',
		defaults:{
			anchor:'95%',
			allowBlank:false
		},
		items:[{
			id:'loginName',
			name:'loginName',
			fieldLabel:'用户名',
			emptyText:'请输入用户名',
			blankText:'用户名不能为空'
		},{
			id:'password',
			name:'password',
			fieldLabel:'密码',
			blankText:'密码不能为空'
		}]							
	}],
	buttons:[{
		text:'登录',
		handler:function(){
			//获取表单对象
			var loginForm = this.ownerCt.findByType('form')[0].getForm();
			alert(loginForm.getValues().loginName);
			loginForm.doAction('submit', {
				url:'ajaxLogin.do',
				method:'POST',						
				waitMsg:'正在登陆...',
				timeout:10000,//10秒超时,
				params:loginForm.getValues(),//获取表单数据
				success:function(form, action){
					var isSuc = action.result.success;
					if(isSuc) {
						//提示用户登陆成功
						Ext.Msg.alert('消息', '登陆成功..');
					}										
				},
				failure:function(form, action){
					alert('登陆失败');
				}
			});
			this.ownerCt.close();
		}
	}, {
		text:'重置',
		handler:function(){
			alert('reset');
			this.ownerCt.findByType('form')[0].getForm().reset();
		}
	}]						
});
winLogin.show();

 注意红色的部分...  这里是得到BaiscForm中所有表单元素中的值,并且已String/Object键值对的形式保存。。 该方法在api文档中的描述如下:

BasicForm getValues API 写道
getValues( [Boolean asString] ) : String/Object

Returns the fields in this form as an object with key/value pairs as they would be submitted using a standard form submit. If multiple fields exist with the same name they are returned as an array.
Parameters:

* asString : Boolean
(optional) false to return the values as an object (defaults to returning as a string)

Returns:

* String/Object

 如此提交解决了提交表单时无法发送数据的问题.... 

到这里终于解决了 如何提交表单的问题...

 

2. 为什么没有执行submit中的success方法, failure方法是在什么时候会被执行..

    这里还是需要 查Action类中的success属性的API文档描述...

Action success属性 API 写道
success : Function

The function to call when a valid success return packet is recieved. The function is passed the following parameters:

* form : Ext.form.BasicForm
The form that requested the action
* action : Ext.form.Action
The Action class. The result property of this object may be examined to perform custom postprocessing.

 这里 success方法需要两个参数, 尤其是第二个参数的描述: 尤其result, 这里是可以点击的

点击后随即跳到了Action result属性的描述: 

Action result属性 API 写道
result : Object

The decoded response object containing a boolean success property and other, action-specific properties.

 有此描述可知,服务器返回的响应中需要包含一个 boolean 型的 success 字段, 该字段会保存在result中,Action会通过获取对该字段的描述 来判断是否执行 success 方法。。

    那么服务器如何返回boolean型的success字段呢?   服务器段部分代码如下:

Java代码 复制代码
  1. try {   
  2.     //返回成功标识   
  3.     <SPAN style="COLOR: #ff0000">response.getWriter().println("{success:true}");</SPAN>   
  4.     response.getWriter().flush();   
  5. catch (IOException e) {   
  6.     e.printStackTrace();   
  7. finally {   
  8.     try {   
  9.         response.getWriter().close();   
  10.     } catch (IOException e) {   
  11.         e.printStackTrace();   
  12.     }   
  13. }  

 

其实form的东西个人觉得还是用ajax提交比较好.
例如:

Javascript代码 复制代码
  1.    var PostVal = baseForm.getForm().getValues();   
  2.    //修改要提交内容的值就很方便了。加入有ID字段,修改它的值只需要这样:   
  3.    PostVal.ID = 2;   
  4.    Ext.Ajax.request({   
  5.       url:'',   
  6.       success:function(response, opts){   
  7. var action = Ext.decode(response.responseText);   
  8.       },   
  9.       params : PostVal   
  10.    });  

 

Java代码 复制代码
  1. request( Object options ) : Number   
  2. Sends an HTTP request to a remote server. Important: Ajax server requests are asynchronous, and this call will retu...   
  3. Sends an HTTP request to a remote server.   
  4.   
  5. Important: Ajax server requests are asynchronous, and this call will return before the response has been received. Process any returned data in a callback function.   
  6. 后台返回格式为 {"success":true,"message":"ok"}   
  7.   
  8. Ext.Ajax.request({   
  9.    url: 'ajax_demo/sample.json',   
  10.    success: function(response, opts) {   
  11.      //Ext.decode 为解析json   
  12.       var obj = Ext.decode(response.responseText);   
  13.       Ext.Msg.alert('',obj.message);   
  14.    },   
  15.    failure: function(response, opts) {   
  16.       console.log('server-side failure with status code ' + response.status);   
  17.    }   
  18. });   
  19. 注意  
request( Object options ) : Number
Sends an HTTP request to a remote server. Important: Ajax server requests are asynchronous, and this call will retu...
Sends an HTTP request to a remote server.

Important: Ajax server requests are asynchronous, and this call will return before the response has been received. Process any returned data in a callback function.
后台返回格式为 {"success":true,"message":"ok"}

Ext.Ajax.request({
   url: 'ajax_demo/sample.json',
   success: function(response, opts) {
     //Ext.decode 为解析json
      var obj = Ext.decode(response.responseText);
      Ext.Msg.alert('',obj.message);
   },
   failure: function(response, opts) {
      console.log('server-side failure with status code ' + response.status);
   }
});
注意

success: function(response, opts)里面的参数顺序
response为需要解析的json
success : Function (Optional)
The function to be called upon success of the request. The callback is passed the following parameters:
response : Object
The XMLHttpRequest object containing the response data.
options : Object
The parameter to the request call.

submit( Object options ) : BasicForm
Shortcut to do a submit action.
Shortcut to do a submit action.
Parameters:
options : Object
The options to pass to the action (see doAction for details).

Note: this is ignored when using the standardSubmit option.

The following code:

myFormPanel.getForm().submit({
    clientValidation: true,
    url: 'updateConsignment.php',
    params: {
        newStatus: 'delivered'
    },
    success: function(form, action) {
       //一样的要注意success: function(form, action)参数问题。最简单的查看方法
        var i = '';
       for(var o in action) i += o + '  ';
       alert(i);
       Ext.Msg.alert('Success', action.result.message);
    },
    failure: function(form, action) {
       Ext.Msg.alert('Failure', action.result.message);
    }
});
would process the following server response for a successful submission:
{
    "success":true, // note this is Boolean, not string
    "msg":"Consignment updated"
}
and the following server response for a failed submission:
{
    "success":false, // note this is Boolean, not string
    "msg":"You do not have permission to perform this operation"
}

 

 

分享到:
评论
2 楼 forrest_lv 2012-04-06  
写的很好,对我帮组很大
1 楼 zwm 2010-08-03  
结合STRUTS2 form提交,有没有尝试过

相关推荐

Global site tag (gtag.js) - Google Analytics