简单的封装了一下ajax通信..

	<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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值