美文网首页
js中ajax封装

js中ajax封装

作者: 清心挽风 | 来源:发表于2017-09-02 19:08 被阅读0次

使用传字符串的形式

html页面代码:

<script type="text/javascript">
            //定义请求成功和请求失败的回调函数
            function successFn(obj){
                console.log(obj);
            }
            function errorFn(err){
                console.log(err);
            }
            
            //调用ajax函数请求数据
            ajaxFn('GET','data.json','',successFn,errorFn);
        </script>

js代码:

//以函数的形式封装ajax请求
//参数:method、data、successFn、errorFn、url
function ajaxFn(method,url,data,successFn,errorFn){
    //创建对象
    var xhr=window.XMLHttpRequest?new XMLHttpRequest():ActiveXObject('Microsoft.XMLHTTP');
    //配置请求对象
    //把请求方法转为大写后再判断
    method=method.toUpperCase();
    if(method=='GET'){
        xhr.open('GET',url+'?'+data,true);
        xhr.send(null);
    }else if(method=='POST'){
        xhr.open('POST',url,true);
        xhr.send(data);
    }else{
        console.error('参数有误,请检查后再调用!!!');
    }
    //监听服务器状态
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4&&xhr.status==200){
            //successFn(xhr.responseText);
            //根据responseXML属性是否为空,判断返回值类型是json还是xml
            var result=xhr.responseXML?xhr.responseXML:xhr.responseText;
            successFn(result);
        }else if(xhr.status==404){
            errorFn('页面找不到');
        }else if(xhr.status==500){
            errorFn('服务器错误');
        }
    }
}

使用对象的形式:

html代码:

<script type="text/javascript">         
            ajax({
                method:"get",
                url:"./data.json",
                data:"",
                successFn:function(obj){
                    console.log(obj);
                },
                errorFn:function(err){
                    console.log(err);
                }
            })
        </script>

js代码:

//通过给函数传递参数的形式(参数是对象类型),实现ajax封装
/**
 * 传递对象作为参数,实现ajax请求
 * @param {object} obj [函数参数,对象类型,obj.method:请求方法,obj.url:
 * 请求接口,obj.data:接口参数,obj.successFn:成功回调,obj.errorFn:失败回调]
 * @return {type} [description]
 */
function ajax(obj){
    var xhr=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP');
    
    method=obj.method.toUpperCase();
    if(method=='GET'){
        xhr.open('GET',obj.url+'?'+obj.data,true);
        xhr.send(null);     
    }else if(method=='POST'){
        xhr.open('POST',obj.url,true);
        xhr.send(obj.data);
    }
    
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4&&xhr.status==200){
            var result=xhr.responseText?xhr.responseText:xhr.responseXML;
            obj.successFn(result);
        }
    }
    
}

![Uploading image_814776.png . . .]

相关文章

网友评论

      本文标题:js中ajax封装

      本文链接:https://www.haomeiwen.com/subject/mkfndxtx.html