本文轉載自:http://blog.csdn.net/dingherry/article/details/6798816
- Ext.Ajax.request({
- url:'http://localhost:8080/myapp/ExtHandler,
- jsonData:Ext.util.JSON.encode(info),
- params:{action:'up'},
- success: function(resp,opts) {
- var respText = Ext.util.JSON.decode(resp.responseText);
- Ext.Msg.alert('提示', respText.info);
- },
- failure: function(resp,opts) {
- var respText = Ext.util.JSON.decode(resp.responseText);
- Ext.Msg.alert('錯誤', respText.error);
- }
- });
代碼中的url參數指定的是一個Java Servlet,通過jsonData參數提交JSON格式的數據到Servlet處理,你也可以提交其它參數,在params參數中定義;然後根據服務器的處理結果Ext.Ajax調用相應成功或失敗的回調函數進行處理;
在Servlet中如何得到jsonData參數中定義的數據呢?看以下代碼:
- StringBuffer json = new StringBuffer();
- String line = null;
- try {
- BufferedReader reader = req.getReader();
- while ((line = reader.readLine()) != null) {
- //讀取jsonData中定義的數據
- json.append(line);
- }
- } catch (Exception e) {
- }
服務端處理數據成功,設置返回信息:
- rsp.setContentType("text/json; charset=utf-8");
- rsp.getWriter().write(
- "{success:false,error:'更新信息失敗,原因爲:" + err + "'}");
- rsp.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED); //設置失敗標識
- //failure回調函數將調用執行,輸出respText.error信息