ajax 封装

var $={};
$.ajax=ajax     //模仿jquery
function ajax(options){
    options=options||{};
    if(!options.url){
        return
    }
    options.type=options.type||'post'; //方法
    options.data=options.data||{};     //内容
    options.timer=options.timer||0;	//超时时间

    var str=jsontourl(options.data)    //data内容转换成字符串
    //1创建ajax对象 并做兼容
    if(XMLHttpRequest){
        var xhr=new XMLHttpRequest()    //高级浏览器
    }else{
        var xhr=new ActiveXObject('Microsoft.XMLHTTP') //低级浏览器
    }

    if(options.type='get'){
        //2创建连接
        xhr.open('get',options.url+'?'+str,true);
        //3发送请求
        xhr.send();
    }else{
        //2创建连接
        xhr.open('post',options.url,true);
        //设置请求头
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
        //3发送请求
        xhr.send(str);
    }

    //4接受请求
    xhr.onreadystatechange=function(){   //当页面加载状态改变的时候
//ajax需要判断2个状态 xhr  http状态

/*
属性readyState的含义
0 ajax对象创建完成 1 连接建立成功 2 数据发送成功 3 接收数据 报文头 响应头 4 接收数据 报文体 响应体 内容*/
/*
  属性status的含义:
0**:未被始化 
1**:请求收到,继续处理 
2**:操作成功收到,分析、接受 
3**:完成此请求必须进一步处理 
4**:请求包含一个错误语法或不能完成 
5**:服务器执行一个完全有效请求失败  */
if(xhr.readyState==4){
            clearTimeout(timer);
            if(xhr.status>=200&&xhr.status<300||xhr.status==304){
                options.success&&options.success(xhr.responseText);
            }else{
                options.error&& options.error(xhr.status)
            }
        }
    }

    if(options.timer){
        var timer = setTimeout(function(){
            alert("超时了!");
            xhr.abort();//终止请求
        },options.timeout);
    }

}
function jsontourl(json){
    var arr=[];
    json.t=Math.random();
    for(var name in json){
        arr.push(name+'='+encodeURIComponent(json[name]));
    }
    return arr.join('&');
}

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值