AJax技术基础

1,什么是Ajax

异步的JavaScript and XML

 

 XMLHttpRequest对一些浏览器不兼容,解决的代码

<script type="text/javascript">
//解决各种浏览器兼容的问题
function getXMLHttpRequest(){
	var xhr = false;
	if(window.XMLHttpRequest){
		xhr = new XMLHttpRequest();	
	}else if(window.ActiveXObject){
		xhr = new ActiveXObject("Microsoft.XMLHTTP");
	}
	return xhr;
}
</script>

 

 Ajax使用的基本步骤

1,获取被点击链接对象

var toAjax = document.getElementById('toAjax');//获取超级链接对象

2,编写链接对象的onclick事件函数,先取消这个链接的默认的onclick事件行为

return false就可以

toAjax.onclick = function(){
      
        return false;//超级链有默认的onclick事件行为(跳转到hello.jsp)
        //先取消这个行为

};

3,编写具体的 ajax方法

3.1获取XMLHttpRequest对象

var xhr = getXMLHttpRequest();

3.2向服务器发送请求
        xhr.open("get","hello.txt");//建立对服务器的调用
        xhr.send();   //向服务器发送请求,发送请求参数

如果是post请求,在send()之前需要设置请求头的编码格式

3.3 用xhr.onreadystatechange属性监听状态的改变,当状态码xhr.readyState变为4时,说明与服务器的交互完成。当xhr.status == 200时,说明发送的请求处理成功,然后做相应的处理。

 

注:onreadystatechange会监听readystate的状态,每一次状态改变都会触发这个事件处理器,代码举例

<%@ 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>Insert title here</title>
<script type="text/javascript">
//解决各种浏览器兼容的问题
function getXMLHttpRequest(){
	var xhr = false;
	if(window.XMLHttpRequest){
		xhr = new XMLHttpRequest();	
	}else if(window.ActiveXObject){
		xhr = new ActiveXObject("Microsoft.XMLHTTP");
	}
	return xhr;
}
window.onload = function (){
	var toAjax = document.getElementById('toAjax');//获取超级链接对象
	
	toAjax.onclick = function(){
		var xhr = getXMLHttpRequest();
		this.hef = this.href+"?id="+ new Date();
		//建立对服务器的调用
		//因为浏览器有缓存,所有要是改变hello.txt里面的内容,再点超链接,新的内容还是没有显示出来
		//xhr.open("get","hello.txt");
		this.hef = this.href+"?id="+ new Date();//所以在请求的URL后面加一个时间戳
		xhr.open("get",this.hef);//url每次点击都会改变,内容时时刻刻更新
		//向服务器发送请求,发送请求参数
		xhr.send();
		//onreadystatechange会监听readystate的状态,每一次状态改变都会触发这个事件处理器
		xhr.onreadystatechange = function(){
			//alert(xhr.readyState);//提示状态码,当是4表示交互完成
			if(xhr.readyState == 4){
				if(xhr.status == 200){
					//alert(xhr.responseText);//获取服务器响应的内容
					var content = document.getElementById('content');
					//把请求得到的内容放入<div id = "content"></div>中
					content.innerHTML = xhr.responseText;
				}else if(xhr.status == 404){
					content.innerHTML = 'no found hello.txt';
				}
			}
		}
		return false;//超级链有默认的onclick事件行为(跳转到hello.jsp)
		//先取消这个行为
	}
};

</script>
</head>
<body>
<a id="toAjax" href="hello.txt">hello</a>
<br>
<div id = "content"></div>
</body>
</html>

 二,js解析json数据

 很多情况下ajax采用jQuery进行封装

注:编写常规的 AJAX 代码并不容易,因为不同的浏览器对 AJAX 的实现并不相同。这意味着您必须编写额外的代码对浏览器进行测试。不过,jQuery 团队为我们解决了这个难题,我们只需要一行简单的代码,就可以实现 AJAX 功能。

具体的使用参考W3CSchool:http://www.w3school.com.cn/jquery/jquery_ajax_intro.asp

猜你喜欢

转载自blog.csdn.net/weixin_42724467/article/details/84135347