Ajax的实现主要依赖于XMLHttpRequest对象,但是在调用其进行异步数据传输时,由于XMLHttpRequest对象的实例在处理事件完成后就会被销毁,所以如果不对该对象进行封装处理,在下次需要调用它时就需要重新构建,而且每次调用都需要写一大段的代码,使用起来很不方便。虽然现在很多开源的Ajax框架都提供了对XMLHttpRequest对象的封装方案,但是如果采用这些框架,通常需要加载很多额外的资源,这势必会浪费很多服务器资源。不过JavaScript脚本语言支持OO编码风格,通过它可以将Ajax所必需的功能封装在对象中。
一、Ajax重构的步骤
Ajax重构大致可以分为以下3个步骤。
1、创建一个单独的JS文件,名称为AjaxRequest.js,并且在该文件中编写Ajax所需的代码。具体代码如下:
var net = new Object(); //定义一个全局变量net
//编写构造函数
net.AjaxRequest = function(url,onload,onerror,method,params){
this.req = null;
this.onload = onload;
this.onerror = (onerror)?onerror:this.defaultError;
this.loadData(url,method,params);
}
//编写用于初始化XMLHttpRequest对象并指定处理函数,最后发送HTTP请求的方法
net.AjaxRequest.prototype.loadDate = function(url,method,params){
if(!method){
method = "GET";
}
if(window.XMLHttpRequest){
this.req = new XMLHttpRequest();
}else id(window.ActiveXObject){
this.req = new ActiveXObject("Microsoft.XMLHTTP");
}
if(this.req){
try{
var loader = this;
this.req.onreadystatechange = function(){
ner.AjaxRequest.onReadyState.call(loader);
}
this.req.open(method,url,true); //建立对服务器的调用
if(method=="POST"){ //如果提交方式为POST
this.req.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //设置请求头
}
this.req.send(params); //发送请求
}catch(err){
this.onerror.call(this);
}
}
}
//重构回调函数
net.AjaxRequest.onReadyState = function(){
var req = this.req;
var ready = req.readyState;
if(ready==4){
if(req.status==200){
this.onload.call(this);
}else{
this.onerror.call(this);
}
}
}
//重构默认的错误处理函数
net.AjaxRequest.prototype.defaultError = function(){
alert("错误数据\n\n 回调状态:"+this.req.readyState+"\n 状态:"+this.req.status);
}
2、在需要应用Ajax的页面中应用以下语句包含步骤1中创建的JS文件。
<script language="JavaScript" src="AjaxRequest.js"></script>
3、在应用Ajax的页面中编写错误处理的方法、实例化Ajax对象的方法和回调函数。具体代码如下。
<script language="JavaScript">
/****************错误处理方法**************/
function onerror(){
alert("您的操作有误!");
}
/****************实例化Ajax对象的方法**************/
function getInfo(){
var loader = new net.AjaxRequest("getInfo.jsp?nocache="+new Date().getTime().deal_getInfo.onerror,"GET");
}
/****************回调函数**************/
function deal_getInfo(){
document.getElementById("showInfo").innerHTML = this.req.responseText;
}
</script>
具体项目中应用我们上面重构的Ajax,将在下一讲向大家介绍,敬请期待。