Ajaxa—使用XMLHttpRequest实现Ajax

一:XMLHttpRequest概述

  1. XMLHttpRequest最早是在IE5中以activeX组件的形式存在,非W3C标准。
  2. 创建XMLHttpRequest对象(由于未标准所以实现方法不同一)
  • IE浏览器把XMLHttpRequest实现为一个activeX对象
  • 其他浏览器把他实现为一个本地的JavaScript对象
  • XMLHttpRequest在不同浏览器上的实现是兼容的,所以可以用同样的方式访问XMLHttpRequest对象的属性和方法,而不论这个实例创建的方法是什么?

 

二:代码实现

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>

<script type="text/javascript">
window.onload=function(){
	//1.获取a节点,并为其添加onclick函数
	document.getElementsByTagName("a")[0].onclick=function(){
		//3.创建XMLHttpRequest对象
		var request=new XMLHttpRequest();
		//4.调用XMLHttpRequest对象的open方法
		var url=this.href;
		var method="GET"
		request.open(method,url);
		
		//5.调用XMLHttpRequest对象的send方法
		request.send(null);
		//6.调用XMLHttpRequest对象的onreadystatechange函数
		 request.onreadystatechange=function(){
			//7.判断响应是否完成,XMLHttpRequest对象的属性readyState属性为4的时候
			if(request.readyState==4){
				//8.判断响应是否可用,XMLHttpRequest对象的status属性值为200时
				if(request.status==200 || request.status==304 ){
					//9.打印响应结果
					alert(request.responseText);
				}
			}
				
		} 
		//2.阻止a标签默认行为
		return false;
		
	}
}

</script>
</head>
<body>
<a href="helloworld.txt">helloworld</a>
</body>
</html>
发布了64 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_39093474/article/details/103668534