1:index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>AJAX入門</title>
<script type="text/javascript">
window.onload=function(){
//1.擷取a節點,並為其添加onclick響應函數
document.getElementsByTagName("a")[0].onclick=function(){
//3.建立一個XMLHttpRequest對象
var request=new XMLHttpRequest();
//4.準備發送請求的資料:url和發送請求的方法
var url=this.href;
var method="GET";
//5.調用XMLHttpRequest對象的open方法(開啟連結)
request.open(method, url);
//6.調用XMLHttpRequest對象的send方法(發送資料)
request.send(null); //get請求的資料會緊跟在URL後面
//7.為XMLHttpRequest對象添加onreadystatechange響應函數
request.onreadystatechange=function(){
//8.判斷響應是否完成:XMLHttpRequest對象的readyState屬性值為4的時候
if(request.readyState==4){
//9.再判斷響應是否可用:XMLHttpRequest對象status屬性值為200或304的時候
if(request.status==200||request.status==304){
//10.列印響應結果:responseText
alert(request.responseText);
}
}
}
//2.取消a節點預設行為
return false;
}
}
</script>
</head>
<body>
<a href="HelloAjax.txt">HelloAjax</a>
</body>
</html>
2: HelloAjax.txt
HelloAjax!^^