下面的兩個頁面講解了一個ajax調用,包括如何建立XMLHttpRequest 對象;如何向伺服器發送請求;如何接收伺服器響應及非同步呼叫的知識。實在是一個不錯的ajax入門樣本。
第一個頁面:
<%@ page contentType="text/html; charset=gb2312"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>ajax 入門樣本</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>
第二個頁面,請求處理頁面:
<%@ page contentType="text/html; charset=gb2312" language="java" errorPage="" %>
<%
String username = new String(request.getParameter("username").getBytes("ISO-8859-1"),"UTF8");
String password = new String(request.getParameter("password").getBytes("ISO-8859-1"),"UTF8");
System.out.println("使用者名稱:"+username);
System.out.println("密碼:"+password);
out.println("使用者名稱和密碼是:" + username +"["+password+"]");
%>