首先看看第一种封装的方式,这种封装方式较为简单,但是在使用的时候方便易容,容易理解ajax的深层次的原理
1获取ajax对象
function ajaxFunction(){
var xmlHttp;
try{ // Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e){
try{// Internet Explorer
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){}
}
}
return xmlHttp;
}
2 ajax打开连接以及调用的封装
function ajax(url,method,data,callback){
//获取xmphttpRquest对象
var xmlHttp=ajaxFunction();
//事件处理程序
xmlHttp.onreadystatechange=function(){
//alert(xmlHttp.readyState);
//alert(xmlHttp.status)
if(xmlHttp.readyState==4){
if(xmlHttp.status==200||xmlHttp.status==304){
//每当服务器的状态发生变化之后,服务器会向ajax引擎返回一系列的
//数据,xmlHttp就是返回来的数据,把这个数据作为callback的形参传递
callback(xmlHttp.responseText);//xmlHttp.responseText为回调函数的实参
}
}
}
//打开连接
xmlHttp.open(method,url,true);
//设置响应头
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//发送请求
xmlHttp.send("data="+data);
}
调用过程
`window.οnlοad=function(){
ajax(“../AjaxServlet”,”post”,null,function(data){//data为回调函数的形参
alert(data);
});
};
回调函数:回调函数的思想就是,在封装ajax对象的时候,callback()这一块封装者不知道调用者需要干什么,谁需要使用,谁就书写回调函数,这样的一种思想
第二种封装方式
function ajax2(ajaxJSON){
//获取xmphttpRquest对象
var xmlHttp=ajaxFunction();
//事件处理程序
xmlHttp.onreadystatechange=function(){
//alert(xmlHttp.readyState);
//alert(xmlHttp.status)
if(xmlHttp.readyState==4){
if(xmlHttp.status==200||xmlHttp.status==304){
ajaxJSON.callback.call(window,xmlHttp.responseText);//xmlHttp.responseText为回调函数的实参
}
}
}
//打开连接
xmlHttp.open(ajaxJSON.method,ajaxJSON.url,true);
//设置响应头
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//发送请求
xmlHttp.send("data="+ajaxJSON.data);
}
调用方式
window.οnlοad=function(){
ajax2({
url:'../AjaxServlet',
method:'post',
data:null,
callback:function(data){
/**
* ajaxJSON.callback(xmlHttp.responseText);//xmlHttp.responseText为回调函数的实参
* 这里的this代表this所在的json对象
* ajaxJSON.callback.call(window,xmlHttp.responseText);//xmlHttp.responseText为回调函数的实参
* 这里的this代表window
*/
alert(this);
}
});
};