2007年03月16日
初試AJAX:中文的傳遞與接收
為 了要讓網頁的頁面與資料傳遞能夠做到更理想,開始研究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
| <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文字框
| <%@
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後才增加的
| 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"); String _sText2 = request.getParameter("TEXT2"); //_sTEXT1 = new String(_sTEXT1.geresponse.setCharacterEncodingtBytes("ISO-8859-1"), "UTF-8"); StringBuffer buf = new StringBuffer(); buf.append("訊息1=" + _sText1); buf.append("訊息2=" + _sText2); out.println(buf.toString()); out.close(); } |
response和request都使用UTF-8就 對了。
完整的 ajax1.html列表在下:
##
引用URL
http://cgi.blog.roodo.com/trackback/2863005

