最简单的提交数据到服务器端的办法就是设置BasicForm的url配置,因为Form Panel封装了BasicForm,这个url直接配置给Form Panel亦可,它会透传给BasicForm的。
Ext.create('Ext.form.Panel', { ... url: 'add_user', items: [ ... ] });
BasicForm的submit方法可以把数据提交到配置的url上:
Ext.create('Ext.form.Panel', { ... url: 'add_user', items: [ ... ], buttons: [ { text: 'Submit', handler: function() { var form = this.up('form').getForm(); // get the basic form if (form.isValid()) { // make sure the form contains valid data before submitting form.submit({ success: function(form, action) { Ext.Msg.alert('Success', action.result.msg); }, failure: function(form, action) { Ext.Msg.alert('Failed', action.result.msg); } }); } else { // display error alert if the data is invalid Ext.Msg.alert('Invalid Data', 'Please correct form errors.') } } } ] });
上面的例子中,button配置了一个处理函数用来处理表单提交,处理函数中做了下面几个动作:
像例子中的表单提交,期望服务器端返回的值,应该像这样:
{ "success": true, "msg": "User added successfully" } 2、Binding a Form to a Model 如何绑定表单和模型
ExtJS中,模型用来定义各种数据,也可以加载和保存数据到服务器。例如一个User模型需要定义User的字段,同时也可以设置代理用来加载和保存数据:
Ext.define('User', { extend: 'Ext.data.Model', fields: ['firstName', 'lastName', 'birthDate'], proxy: { type: 'ajax', api: { read: 'data/get_user', update: 'data/update_user' }, reader: { type: 'json', root: 'users' } } });有关模型的更多内容请查看<ExtJS 4 数据(包)详解>
数据可以通过loadRecord方法直接从Model加载进入Form Panel:
Ext.ModelMgr.getModel('User').load(1, { // load user with ID of "1" success: function(user) { userForm.loadRecord(user); // when user is loaded successfully, load the data into the form } });最后,代替submit方法,可以使用BasicForm的updateRecord方法更新form绑定的model,然后用Model的save方法保存数据:
Ext.create('Ext.form.Panel', { ... url: 'add_user', items: [ ... ], buttons: [ { text: 'Submit', handler: function() { var form = this.up('form').getForm(), // get the basic form record = form.getRecord(); // get the underlying model instance if (form.isValid()) { // make sure the form contains valid data before submitting form.updateRecord(record); // update the record with the form data record.save({ // save the record to the server success: function(user) { Ext.Msg.alert('Success', 'User saved successfully.') }, failure: function(user) { Ext.Msg.alert('Failure', 'Failed to save user.') } }); } else { // display error alert if the data is invalid Ext.Msg.alert('Invalid Data', 'Please correct form errors.') } } } ] });3、 使用store提交。
如果使用ajax方式。
api : ObjectSpecific urls to call on CRUD action methods "create", "read", "update" and "destroy". Defaults to:
api: { create : undefined, read : undefined, update : undefined, destroy : undefined }The url is built based upon the action being executed [create|read|update|destroy] using the commensurate api property, or if undefined default to the configured Ext.data.Store.url.
For example:
api: { create : '/controller/new', read : '/controller/load', update : '/controller/update', destroy : '/controller/destroy_action' }
之前总是封不起Extjs中form.submit()提交与Ext.Ajax.request()的区别,现在仍是分不清,但是知道怎么用不会出错了。
方案1:
java action中的代码
Java代码
- String datastring = "total : " + rehpage.getCount() + ", root : [";
- if (rehpage != null) {
- datastring += buildJsonByPage(rehpage);
- }
- datastring = datastring + "]";
- StringBuffer buff = new StringBuffer("{success:true,mes:{");
- buff.append(datastring);
- buff.append("}}");
- System.out.println("datastring is: " + buff.toString());
- request.setAttribute("responseText", buff.toString().replaceAll("\r\n",
- " ").replaceAll("\n", " "));// 将拼接好的数据放到request
- return SUCCESS;
对用的Extjs中的代码为:
Java代码
- Ext.Ajax.request({
- url : "./rehearsal/queryTableData.action",
- params : {
- search_place : rehearsal_place,
- search_time : dt
- .format('Y-m-d'),
- search_valuation : null,
- search_subject : search_subject
- },
- waitMsg : '正在提交数据',
- waitTitle : '提示',
- method : "POST",
- success : function(response) {
- var respText = Ext.util.JSON
- .decode(response.responseText);
- if (respText.success) {
- szcdc_rehearsal_one_grid
- .getStore()
- .loadData(respText.mes);
- }
- },
- failure : function(response) {
- Ext.Msg.alert('提示',
- "操作失败:输入非法字符!!!");
- }
- });
- }
方案2:
java action中的代码是:
Java代码
- String datastring = "total : " + rehpage.getCount() + ", root : [";
- if (rehpage != null) {
- datastring += buildJsonByPage(rehpage);
- }
- datastring = datastring + "]";
- StringBuffer buff = new StringBuffer("{success:true,");
- buff.append(datastring);
- buff.append("}");
- System.out.println("datastring is: " + buff.toString());
- request.setAttribute("responseText", buff.toString().replaceAll("\r\n",
- " ").replaceAll("\n", " "));// 将拼接好的数据放到request
- return SUCCESS;
对应的Extjs代码为:
Java代码
- search_form.submit({
- url : "./rehearsal/queryTableData.action",
- baseParams : {
- search_place : rehearsal_place,
- search_time : search_time,
- search_valuation : search_valuation,
- search_subject : search_subject
- },
- waitMsg : '正在提交数据',
- waitTitle : '提示',
- method : "POST",
- success : function(form, action) {
- // 得到数据
- var result = Ext.util.JSON
- .decode(action.response.responseText);// 就可以取出来。如果是数组,那么很简单
- // 把数据放到结果里面
- szcdc_rehearsal_one_grid.getStore()
- .loadData(result);
- },
- failure : function(form, action) {
- Ext.Msg.alert('提示', "操作失败:输入非法字符!!!");
- }
- });
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title></title>
- <!--ExtJs4.0官方下载ExtJs样式文件-->
- <link href="extjs/resources/css/ext-all.css" rel="stylesheet" type="text/css" />
- <!--ExtJs4.0官方下载ExtJs文件-->
- <script src="extjs/ext-all.js" type="text/javascript"></script>
- <script language="javascript" type="text/javascript">
- function login_click(b) {
- //1.拿到表单面板
- var loginFormPanel=Ext.getCmp("loginFormPanel");
- //2.通过面板对象拿到它里面的表单
- var form = loginFormPanel.getForm();
- //3.在提交前,判断表单输入是否有误
- if (!form.isValid()) {
- return;
- }
- //4.调用提交的方法,提交该表单
- form.submit({
- waitMsg:"正在向服务器提交数据",
- url:"Extjs1.aspx",
- success: function (f, a) {
- Ext.MessageBox.alert("提示", "你的详细信息如下:<br/>用户名:" + a.result.name + "<br/>密 码:" + a.result.password + "<br/>你上传的图片数量为:"
- + a.result.filecount);
- },
- failure: function (f,a) {
- Ext.MessageBox.alert("提示", a.result.msg);
- }
- });
- }
- Ext.onReady(function () {
- var txtUserName = new Ext.form.field.Text({
- fieldLabel: "用户名",
- labelWidth: 50,
- margin: "10 0 5 0",
- allowBlank: false,
- blankText: "用户名不能为空",
- name: "txtUserName"
- });
- var txtUserPassword = new Ext.form.field.Text({
- fieldLabel: "密 码",
- labelWidth: 50,
- margin: "5 0 5 0",
- inputType: "password",
- allowBlank: false,
- blankText: "密码不能为空",
- name: "txtUserPassword"
- });
- var file = new Ext.form.field.File({
- fieldLabel:"请选择一张图片",
- buttonText:"浏览",
- regex:/^.+\.(jpg|png|gif)$/,
- regexText:"你只能选择jpg,png,gif格式的图片"
- });
- var win = new Ext.window.Window({
- title: "提交数据——登录",
- height: 200,
- width: 350,
- layout: "fit",
- items: [
- { xtype: "form", frame: true, layout: { type: "vbox", align: "center" },
[javascript] view plain copy print ?
- items: [txtUserName, txtUserPassword, file], buttons: [{ text: "登录",
- handler: login_click}], id: "loginFormPanel" }
- ]
- });
- win.show();
- });
- </script>
- </head>
- <body>
- </body>
- </html>
//Extjs1.aspx.cs[csharp] view plain copy print ?
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- public partial class Extjs1 : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- System.Threading.Thread.Sleep(3000);
- string name = Request.Form["txtUserName"];
- string password = Request.Form["txtUserPassword"];
- //.............................
- int pointIndex=Request.Files[0].FileName.LastIndexOf(".");
- string lastName=Request.Files[0].FileName.Substring(pointIndex);
- string fileName = new Random().Next(10000).ToString();
- string path = Server.MapPath("") + "/" + fileName + lastName;
- Request.Files[0].SaveAs(path);
- Response.Write("{success:true,msg:'成功',name:'"+name+"',password:'"+password+"',filecount:'"+Request.Files.Count+"'}");
- Response.End();
- }
- }
效果预览如下: