Ajax全稱為“Asynchronous JavaScript and XML”(異步JavaScript和XML),是指一種創(chuàng)建交互式網(wǎng)頁應用的網(wǎng)頁開發(fā)技術。Ajax技術是目前在瀏覽器中通過JavaScript腳本可以使用的所有技術的集合。Ajax以一種嶄新的方式來使用所有的這些技術,使得古老的B/S方式的Web開發(fā)煥發(fā)了新的活力。
ajax()方法是jQuery底層的ajax實現(xiàn),通過HTTP請求加載遠程數(shù)據(jù)。
$.ajax({type: "GET",url: "handleAjaxRequest.action",data: {paramKey:paramValue},async: true,dataType:"json",success: function(returnedData) {alert(returnedData);//請求成功后的回調(diào)函數(shù)//returnedData--由服務器返回,并根據(jù) dataType 參數(shù)進行處理后的數(shù)據(jù);//根據(jù)返回的數(shù)據(jù)進行業(yè)務處理},error: function(e) {alert(e);//請求失敗時調(diào)用此函數(shù)}});}
參數(shù)說明:
type:請求方式,“POST”或者“GET”,默認為“GET”。
url:發(fā)送請求的地址。
data:要向服務器傳遞的數(shù)據(jù),已key:value的形式書寫(id:1)。GET請求會附加到url后面。
async:默認true,為異步請求,設置為false,則為同步請求。
dataType:預期服務器返回的數(shù)據(jù)類型,可以不指定。有xml、html、text等。
在開發(fā)中,使用以上參數(shù)已可以滿足基本需求。
如果需要向服務器傳遞中文參數(shù),可將參數(shù)寫在url后面,用encodeURI編碼就可以了。
var chinese = "中文";var urlTemp = "handleAjaxRequest.action?chinese="+chinese;var url = encodeURI(urlTemp);//進行編碼$.ajax({type: "GET",url: url,//直接寫編碼后的urlsuccess: function(returnedData) {alert(returnedData);//請求成功后的回調(diào)函數(shù)//returnedData--由服務器返回,并根據(jù) dataType 參數(shù)進行處理后的數(shù)據(jù);//根據(jù)返回的數(shù)據(jù)進行業(yè)務處理},error: function(e) {alert(e);//請求失敗時調(diào)用此函數(shù)}});}
struts2的action對請求進行處理:
public void handleAjaxRequest() {HttpServletRequest request = ServletActionContext.getRequest();HttpServletResponse response = ServletActionContext.getResponse();//設置返回數(shù)據(jù)為html文本格式response.setContentType("text/html;charset=utf-");response.setHeader("pragma", "no-cache");response.setHeader("cache-control", "no-cache");PrintWriter out =null;try {String chinese = request.getParameter("chinese");//參數(shù)值是中文,需要進行轉(zhuǎn)換chinese = new String(chinese.getBytes("ISO--"),"utf-");System.out.println("chinese is : "+chinese);//業(yè)務處理String resultData = "hello world";out = response.getWriter();out.write(resultData);//如果返回json數(shù)據(jù),response.setContentType("application/json;charset=utf-");//Gson gson = new Gson();//String result = gson.toJson(resultData);//用Gson將數(shù)據(jù)轉(zhuǎn)換為json格式//out.write(result);out.flush();}catch(Exception e) {e.printStackTrace();}finally {if(out != null) {out.close();}}}
|
新聞熱點
疑難解答
圖片精選