1. 程式人生 > >Ext.Ajax獲取返回值(引數)

Ext.Ajax獲取返回值(引數)

本文轉載自:http://blog.csdn.net/dingherry/article/details/6798816

[javascript] view plain copy
  1. Ext.Ajax.request({  
  2.                     url:'http://localhost:8080/myapp/ExtHandler,
  3.                     jsonData:Ext.util.JSON.encode(info),  
  4.                     params:{action:'up'},  
  5.                     success: function
    (resp,opts) {  
  6.                             var respText = Ext.util.JSON.decode(resp.responseText);                       
  7.                             Ext.Msg.alert('提示', respText.info);  
  8.                     },  
  9.                     failure: function(resp,opts) {  
  10.                             var respText = Ext.util.JSON.decode(resp.responseText);  
  11.                             Ext.Msg.alert('錯誤', respText.error);  
  12.                    }  
  13.    });  

程式碼中的url引數指定的是一個Java Servlet,通過jsonData引數提交JSON格式的資料到Servlet處理,你也可以提交其它引數,在params引數中定義;然後根據伺服器的處理結果Ext.Ajax呼叫相應成功或失敗的回撥函式進行處理;

在Servlet中如何得到jsonData引數中定義的資料呢?看以下程式碼:

  1. StringBuffer json = new StringBuffer();    
  2. String line = null;      
  3. try {       
  4.     BufferedReader reader = req.getReader();      
  5.     while ((line = reader.readLine()) != null)  {  
  6.             //讀取jsonData中定義的資料  
  7.           json.append(line);      
  8.     }  
  9. catch (Exception e) {      
  10. }      

服務端處理資料成功,設定返回資訊:

[javascript] view plain copy
  1. rsp.setContentType("text/json; charset=utf-8");  
  2. rsp.getWriter().write(  
  3.     "{success:false,error:'更新資訊失敗,原因為:" + err + "'}");  
  4. rsp.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);     //設定失敗標識
  5. //failure回撥函式將呼叫執行,輸出respText.error資訊