天天看点

前后端数据交互ajax(Asynchronous Javascript And XML)前后端数据交互ajax

前后端数据交互ajax

ajax是异步JavaScript和XML;主要用于前后端数据交互,通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

如何创建ajax?

  • 创建ajax对象
考虑兼容创建ajax对象
    if(window.XMLHttpRequest){
        //ie6+
        var oAjax = new XMLHttpRequest();
    }else{
        //ie6
        var oAjax = new ActiveXObject('Microsoft.XMLHTTP');
    }
           
  • 打开地址
//GET和POST方法
oAjax.open('GET',URL+'?'+拼接好的数据,true);
oAjax.open('POST',URL,true);
           
  • 数据的提交方式
一般采用GET和POST提交数据
    //GET方法提交
    oAjax.send();
    //POST方法提交(需要设置请求头)
    oAjax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    oAjax.send(json2url(json.data));
           
  • 接收数据
oAjax.onreadystatechange=function(){
        if(oAjax.readyState==){
            if(oAjax.status>= && oAjax.status< || oAjax.status==){
                //数据
                oAjax.responseText
            }else{
                //获取失败返回http状态码
                oAjax.status
            }
        }
    };
           

下面进行具体的封装:

//拼接数据的函数,后面加了时间戳用于防止缓存
function json2url(json){
    var oDate=new Date();
    json.t=oDate.getTime();
    var arr=[];
    for(var name in json){
        arr.push(name+'='+json[name]);
    };
    return arr.join('&');
}
//url,data,type,fnSucc,fnFail,loading
function ajax(json){
    json=json || {};
    json.data=json.data || {};
    json.type=json.type || 'get';
    json.time=json.time || ;
    if(!json.url){
        return;
    }
    //创建ajax对象 兼容ie6
    if(window.XMLHttpRequest){
        var oAjax=new XMLHttpRequest();
    }else{
        var oAjax=new ActiveXObject('Microsoft.XMLHTTP');
    }
    //判断数据发送方式
    switch(json.type.toLowerCase()){
        case 'get':
        oAjax.open('GET',json.url+'?'+json2url(json.data),true);
            oAjax.send();
        break;
        case 'post':
            oAjax.open('POST',json.url,true);
            //post方法要设置请求头
            oAjax.setRequestHeader('content-type','application/x-www-form-urlencoded');
            oAjax.send(json2url(json.data));
        break;
    }
    //数据加载时可加入loading函数
    json.loading && json.loading();
    //资源加载情况
    oAjax.onreadystatechange=function(){    
        if(oAjax.readyState==){
            //http状态码
            if((oAjax.status>=&&oAjax.status<)||oAjax.status==){
                json.success&&json.success(oAjax.responseText);
            }else{
                json.fail&&json.fail(oAjax.status);
            }
            json.complete && json.complete();
            clearTimeout(timer);
        }
    };
    var timer=null;
    //一定时间数据取不会来则提示信息
    timer=setTimeout(function(){
        alert('请求超时');
        oAjax.onreadystatechange=null;
    },json.time)
}
//调用
ajax({
    url:URL,
    data:{数据(json格式)},
    type:post/get,
    loading:function(){},
    success:function(){},
    fail:function(){},
})
           

继续阅读