
為了要讓網頁的頁面與資料傳遞能夠做到更理想,開始研究AJAX,試看看是否能透過AJAX來解決部份以GET方式而受到的限制能有所突破。以下將測試環境與程式按步就班地呈現出來,測試的過程裡,特別針對中文的傳入與傳回做了較詳盡的反覆測試。
測試環境:
- 作業系統:Windows 2003 Server
- 瀏覽器:IE 6.0.3790.0、FireFox 2.0.0.2
- Application Server:Resin 2.12、Resin 3.0.21
首先撰寫啟始的前端網頁文件,命名為 ajax.html,網頁裡放三個控制項,一個用來輸入文字的TEXT1、觸發AJAX執行的按鈕btnOK1和接收Server回應的文字框RESULT,呈現頁面如圖2。
| <form id=”idForm”> <input type=”text” name=”TEXT1″ id=”TEXT1″> <input type=”button” name=”btnOK1″ id=”btnOK1″ value=” TEST 1 “> <textarea name=”RESULT” id=”RESULT” rows=10 cols=50></textarea> </form> |
| 圖2 |
![]() |
把按鈕RESULT的 onclick 事件放在window.onload裡:
| window.onload = function() { document.getElementById(“btnOK1″).onclick = function() { request = httpRequest(); document.getElementById(“RESULT”).innerHTML = “”; request.open(“POST”, “ajax2.jsp”, true); request.onreadystatechange = handleResponse; request.setRequestHeader(“Content-Type”, “application/x-www-form-urlencoded;”); request.send(“TEXT1=” + document.getElementById(“TEXT1″).value + “&TEXT2=中文傳到Server”); } //~ btnOK1 } //~ window.onload |
幾個說明如下:
- XMLHttpRequest物件建立後,變數名稱是request
- 用了避免傳遞的參數有字數長度的限制,因此用POST的方式傳參數;使用POST傳遞參數時,必須有request.setRequestHeader,此處必須特別注意的是:request.setRequestHeader必須寫在request.open後面,否則 IE 會有”錯誤:無法指出的錯誤”,而FireFox會有”uncaught exception”錯誤
- Query String會以問號開頭,而使用request.send傳送時不能用問號開頭!
- Server的處理程式檔名為 ajax2.jsp
- Server處理完畢後會被執行的函數是
handleResponse,把接收回的字串寫入RESULT文字框
Server上的 ajax2.jsp 主要邏輯如下:
| <%@ page contentType=”text/html;charset=UTF-8″%> <% //response.setContentType(“text/html;charset=UTF-8″); //response.setHeader(“Charset”, “Big5″); request.setCharacterEncoding(“UTF-8″); out.println(“由Server輸出回網頁…..”); String _sText1 = request.getParameter(“TEXT1″); out.println(“TEXT1=” + _sText1); %> |
重點說明:
- XMLHttpRequest傳出與接收的編碼都是UTF-8,因此JSP的反應編碼(第一行)與接收傳入參數的request(第5行)都使用UTF-8,如此接進來的參數與傳回的輸出,才能正確的被XMLHttpRequest處理
- 有的網站會把request參數用ISO8859-1再編碼成UTF-8,或用response.setCharacterEncoding設定UTF-8,其實只要用說明1的方法就能都解決了;另外,若使用的Application Server使用的是JSDK 2.3的話,是無法使用response.setCharacterEncoding的,這個method是JSDK 2.4後才增加的
再來把 ajax1.html 的Server換用Servlet來處理(xxx換成自己的Webapp名稱):
| request.open(“POST”, “/xxx/servlet/ajax_Servlet2″, true); |
ajax_Server2的主要邏輯是:
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(“text/html; charset=UTF-8″); request.setCharacterEncoding(“UTF-8″); PrintWriter out = response.getWriter(); String _sText1 =request.getParameter(“TEXT1″); //_sTEXT1 = new |
response和request都使用UTF-8就對了。
完整的 ajax1.html列表在下:
##












最新留言