這兩天在繼續我的Ajax之旅。一直在抓緊步伐。
前天試驗使用Ajax提交form表單到服務器,獲取form信息內容出現了亂碼,一時無法解決。網上有結論說是application/x-www-form-urlencoded編碼的原因,我估計也是。正在尋找解決之道。
大家一起討論討論。
2005-12-05 11:20 補充:
通過在后臺用UTF8轉碼的方式可以解決中文亂碼問題。這種方法針對form表單提交,編碼在服務器完成。代碼如下:
form.jsp:
<%@ page contentType="text/html; charset=gb2312"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>表單提交測試</title>
<script language="javascript">
var http_request = false;
function send_request(url,poststr) {//初始化、指定處理函數、發送請求的函數
http_request = false;
//開始初始化XMLHttpRequest對象
if(window.XMLHttpRequest) { //Mozilla 瀏覽器
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {//設置MiME類別
http_request.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject) { // IE瀏覽器
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) { // 異常,創建對象實例失敗
window.alert("不能創建XMLHttpRequest對象實例.");
return false;
}
http_request.onreadystatechange = processRequest;
// 確定發送請求的方式和URL以及是否同步執行下段代碼
http_request.open("POST", url, true);
http_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
http_request.send(poststr);
}
// 處理返回信息的函數
function processRequest() {
if (http_request.readyState == 4) { // 判斷對象狀態
if (http_request.status == 200) { // 信息已經成功返回,開始處理信息
alert(http_request.responseText);
} else { //頁面不正常
alert("您所請求的頁面有異常。");
}
}
}
function form_submit() {
var f = document.form1;
var username = f.username.value;
var password = f.password.value;
var poststr = "";
if(username=="") {
window.alert("用戶名不能為空。");
f.username.focus();
return false;
}
if(password=="") {
window.alert("密碼不能為空。");
f.password.focus();
return false;
}
poststr = "username="+encodeURI(f.username.value)+"&password="+f.password.value;
send_request('form_handle.jsp',poststr);
return false;
}
</script>
</head>
<body>
<form name="form1" method="post" action="" onsubmit="return form_submit()">
<table width="300" border="0" cellspacing="4" cellpadding="0" style=" font-size:12pt;">
<tr>
<td width="74" height="25">用戶名:</td>
<td width="220" height="25"><input name="username" type="text" id="username" size="20"></td>
</tr>
<tr>
<td height="25">密碼:</td>
<td height="25"><input name="password" type="password" id="password" size="20"></td>
</tr>
<tr align="center">
<td height="25" colspan="2"><input type="submit" name="Submit" value="提交"></td>
</tr>
</table>
</form>
</body>
</html>
form_handle.jsp:
<%@ page contentType="text/html; charset=gb2312" language="java" errorPage="" %>
<%
String username = new String(request.getParameter("username").getBytes("ISO-8859-1"),"UTF8");
String password = request.getParameter("password");
System.out.println("用戶名:"+username);
System.out.println("密碼:"+password);
out.println(username+"|"+password);
%>
另外,有些網友反應生成包含中文內容的XML文檔返回到客戶端也會出現亂碼問題。建議將XML文檔的編碼方式改成UTF8試試看。
期待大家的反饋。