一,为什么要对Ajax进行重构?
Ajax的实现主要依赖于XMLHttpRequest对象, 但在调用其进行异步数据传输时,由于XMLHttpRequest对象的实例在处理完事件后就会被自动销毁,如果不对该对象进行封装处理,每次调用就要重新构建,需要在写一大段代码,很不方便。虽然很多的开源的Ajax框架提供了对XMLHttpRequest对象的封装方案,但是使用框架,就会加载很多不必要的资源,会浪费服务器的资源。JavaScript脚本语言支持OO编码风格,通过它可以将Ajax所必需的功能封装在对象中
二,Ajax重构的步骤
1.创建一个单独的JS文件,名称为AjaxRequest.js。并且在该文件中编写重构Ajax所需的代码
示例:
var net =new Object();
//编写构造函数
net.AjaxRequest=function(url,onload,onerror,method,params){
this.req=null;
this.onload=onload;
this.onerror=(onerror)?onerror:this.defaultError;
this.lodaDate(url,method,params);
}
//编写用于初始化XMLHttpRequest对象并指定处理函数,最后发送HTTP请求
net.AjaxRequest.prototype.loadDate=function(url,method,params){
if(!method)
{
method="GET";
}
if(window.XMLHttpReq)
{
this.req=new XMLHttpRequest();
}else if(window.ActiveXObject){
this.req=new ActiveXObject("Microsoft.XMLHTTP");
}
if(this.req)
{
try{
var loader=this;
this.req.onreadystatechange=function()
{
net.AjaxRequest.onReadyStatae.call(loader);
}
this.req.open(method, url, true); //建立对服务器的调用
if(method=="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="JS/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>