<script>
//a继承b
function Extend(a,b){
for(var pro in b)
a[pro] = b[pro];
}
//ajax 类
function ajax(opts){
this.xhr = false;
//默认值
this.opts = {
method : "get",//请求方式
url : "",//请求地址
asynch : true ,//是否异步
callBack : function(xhr){},//用户的回调函数
content : null,//send()方法的参数
readyState : 4,//请求的状态,有5个可取值:0 = 未初始化,1 = 正在加载,2 = 已加载,3 = 交互中,4 = 完成
status : 200 //服务器的HTTP状态码(200对应OK,404对应Not Found(未找到),等等)
}
//赋值
Extend(this.opts,opts);
/*创建XHR对象*/
this.createXHR = function(){
if(window.XMLHttpRequest)
this.xhr = new XMLHttpRequest();
else if(window.ActiveXObject)
this.xhr = new ActiveXObject("Microsoft.XMLHTTP");
};
/*发送请求*/
this.doRequest = function(){
this.xhr.onreadystatechange = (function(ajaxer){
return function(){
ajaxer.realCall();
}
})(this);
this.xhr.open(this.opts.method,this.opts.url,this.opts.asynch);
this.xhr.send(this.opts.content);
};
/*真正的回调函数*/
this.realCall = function(){
if(this.xhr == null)
return;
if(this.xhr.readyState == this.opts.readyState)
{
if(this.xhr.status == this.opts.status)
{
this.opts.callBack(this.xhr);
}
}
};
this.createXHR();
this.doRequest();
}
//声明一个ajax参数所需要的参数
var getRelateds = {
method : "post",//请求方式
url : "related.xml",//请求地址
asynch : true ,//是否异步
callBack : function(xhr){document.write(xhr.responseText);},//用户的回调函数
content : null
};
//创建一个ajax实例..
var ajax1 = new ajax(getRelateds);
</script>
简单的封装了一下ajax通信..
最新推荐文章于 2021-08-06 14:34:10 发布