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="" >
<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試試看。