var net=new Object();
net.READY_STATE_UNINITIALIZED=0;
net.READY_STATE_LOADING=1;
net.READY_STATE_LOADED=2;
net.READY_STATE_INTERACTIVE=3;
net.READY_STATE_COMPLETE=4;
/*--- content loader object for cross-browser requests ---*/
net.ContentLoader=function(url,onload,onerror,method,params,contentType){
this.req=null;
this.onload=onload;
this.onerror=(onerror) ? onerror : this.defaultError;
this.loadXMLDoc(url,method,params,contentType);
}
net.ContentLoader.prototype.loadXMLDoc=function(url,method,params,contentType){
if (!method){
method="GET";
}
if (!contentType && method=="POST"){
contentType='application/x-www-form-urlencoded';
}
if (window.XMLHttpRequest){
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.ContentLoader.onReadyState.call(loader);
}
this.req.open(method,url,true);
if (contentType){
this.req.setRequestHeader('Content-Type', contentType);
}
this.req.send(params);
}catch (err){
this.onerror.call(this);
}
}
}
net.ContentLoader.onReadyState=function(){
var req=this.req;
var ready=req.readyState;
var httpStatus=req.status;
if (ready==net.READY_STATE_COMPLETE){
if (httpStatus==200 || httpStatus==0){
this.onload.call(this);
}else{
this.onerror.call(this);
}
}
}
net.ContentLoader.prototype.defaultError=function(){
alert("error fetching data!"
+"/n/nreadyState:"+this.req.readyState
+"/nstatus: "+this.req.status
+"/nheaders: "+this.req.getAllResponseHeaders());
}
本质上就是以OO的方式构造了一个net对象,通过它来实现AJAX调用,构造函数必需的就两个参数:URL和回调函数(也就是你要处理服务器返回文档的函数),其他就是参数,方法,返回类型等。
写了一个简单的例子调用这个框架:
<script type='text/javascript' src='ContentLoader.js'></script>
<script type='text/javascript'>
window.onload=function(){
var loader1=new net.ContentLoader("data.txt",displayResult);
}
function displayResult(){
var tmp=document.getElementById("hello");
var txt=this.req.responseText;
alert(txt);
var childEl=document.createElement("div");
var textNode=document.createTextNode(txt);
childEl.appendChild(textNode);
tmp.appendChild(childEl);
}
</script>
<div id="hello"></div>
此例中的回调函数就是displayResult()方法,url为同个文件夹下面的data.txt,很简单的例子,显示data.txt中的内容。在其他函数中,你完全可以通过this来调用net对象,如上例中this.req.responseText,具体不再详述