XMLHttpRequest最早是在IE5中以ActiveX组件的形式实现的。非W3C标准。
创建XMLHttpRequest对象
function getHTTPObject(){
var xhr = false;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}
else if(window.ActiveObject){
xhr = new ActiveObject("Microsoft.XMLHTTP");
}
return xhr;
}
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<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);
//7. 为XMLHttpRequest对象添加onreadystatechange响应函数
request.onreadystatechange = function(){
//8. 判断响应是否完成:XMLHttpRequest对象的readyState属性值为4的时候
if(request.readyState == 4){
//9. 再判断响应是否可用:XMLHttpRequest对象的status的属性值为200
if(request.status == 200 || request.status == 304){
//10. 打印响应结果
alert(request.responseText);
}
}
}
//2. 取消a节点的默认行为
return false;
}
}
</script>
<body>
<a href="helloAjax.txt">Hello Ajax</a>
</body>
</html>