ExtJS 作為企業級 Web 應用框架,提供了豐富的 Ajax 封裝。本文總結四種常用的異步提交模式,適用於表單提交、數據保存等場景。
最基礎用法,完全手動構建參數對象,靈活度最高。
function saveUser_ajaxSubmit1() {
Ext.Ajax.request({
url: 'user_save.action',
method: 'post',
params: {
userName: document.getElementById('userName').value,
password: document.getElementById('password').value
},
success: function(response, options) {
var o = Ext.util.JSON.decode(response.responseText);
alert(o.msg);
},
failure: function() {
alert('請求失敗');
}
});
}
適用場景:參數簡單、需精確控制發送數據、非表單場景。
利用 form 參數直接指定現有 <form> 元素 ID,自動序列化表單數據。
function saveUser_ajaxSubmit2() {
Ext.Ajax.request({
url: 'user_save.action',
method: 'post',
form: 'userForm', // 指定表單 ID
success: function(response, options) {
var o = Ext.util.JSON.decode(response.responseText);
alert(o.msg);
},
failure: function() {
alert('請求失敗');
}
});
}
適用場景:頁面已有原生 HTML 表單,想快速複用無需手動取值。
使用 Ext 組件構建表單與彈窗,內建驗證、等待提示、提交處理。
function saveUser_ajaxSubmit3() {
var formPanel = new Ext.FormPanel({
labelWidth: 75,
frame: true,
bodyStyle: 'padding:5px 5px 0',
width: 350,
defaults: { width: 230 },
defaultType: 'textfield',
items: [{
fieldLabel: '用戶名',
name: 'userName',
allowBlank: false
}, {
fieldLabel: '密碼',
name: 'password',
inputType: 'password'
}]
});
var win = new Ext.Window({
title: '添加用戶',
layout: 'fit',
width: 500,
height: 300,
closeAction: 'close',
closable: false,
plain: true,
items: formPanel,
buttons: [{
text: '確定',
handler: function() {
var form = formPanel.getForm();
var userName = form.findField('userName').getValue().trim();
var password = form.findField('password').getValue().trim();
if (!userName) { alert('用戶名不能為空'); return; }
if (!password) { alert('密碼不能為空'); return; }
form.submit({
waitTitle: '請稍後...',
waitMsg: '正在保存用戶信息,請稍後...',
url: 'user_save.action',
method: 'post',
success: function(form, action) {
alert(action.result.msg);
win.close();
},
failure: function(form, action) {
alert(action.result.msg);
}
});
}
}, {
text: '取消',
handler: function() { win.close(); }
}]
});
win.show();
}
適用場景:需要豐富 UI 交互(驗證、遮罩、彈窗)的標準表單操作。
將原生 <form> 包裝為 Ext 表單對象,調用 submit() 實現異步提交。
function saveUser_ajaxSubmit4() {
new Ext.form.BasicForm('userForm').submit({
waitTitle: '請稍後...',
waitMsg: '正在保存用戶信息,請稍後...',
url: 'user_save.action',
method: 'post',
success: function(form, action) {
alert(action.result.msg);
},
failure: function(form, action) {
alert(action.result.msg);
}
});
}
適用場景:頁面已有傳統 HTML 表單,想以最小改動接入 ExtJS 異步提交流程。
| 方式 | 核心API | 優點 | 缺點 | 推薦場景 |
|---|---|---|---|---|
| 1. 手動參數 | Ext.Ajax.request(params) | 完全可控、無依賴 | 樣板代碼多、易出錯 | 簡單接口、非表單數據 |
| 2. 指定HTML表單 | Ext.Ajax.request(form) | 零侵入、快速接入 | 無客戶端驗證、UI反饋弱 | 現有表單快速Ajax化 |
| 3. Ext組件表單 | FormPanel + Window | 功能最全(驗證/遮罩/彈窗) | 代碼量大、學習曲線陡 | 標準化表單交互、複雜驗證 |
| 4. BasicForm包裝 | Ext.form.BasicForm.submit() | 輕量、保留原生表單結構 | 功能介於2和3之間 | 漸進式遷移legacy表單 |
failure 回調,處理 HTTP 錯誤碼、Session 過期、業務錯誤碼{success: true, msg: '', data: {}}vtype、regex、自定義 VTypeExt.data.Model + Ext.form.Panel 雙向綁定