Don’t know how to use ajax? Teach you how to encapsulate a convenient and easy-to-use ajax

Don’t know how to use ajax? Teach you how to encapsulate a convenient and easy-to-use ajax

1. How to prepare work

Determine whether it is an object
function isObject(arg){
    
    
    return (typeof arg === "object" && arg !== null && arg.constructor && arg.constructor === Object);
} 
Modify date/url according to request method
function toUrlData(data,url,method){
    
    
    if(isObject(data)){
    
    
        var html = "";
        for(var attr in data){
    
    
            html += "&" + attr + "=" + data[attr];
        }
        html = html.slice(1);
        method = method || "";
        if(method.toUpperCase() === "POST"){
    
    
            return html;
        }
        url += "?" + html;
        return url;
    }
    return url;
}
Merge objects
  function assign(){
    
    
        var target = arguments[0];
        for(var i = 1 ; i <arguments.length; i ++){
    
    
            for(var attr in arguments[i]){
    
    
                target[attr] = arguments[i][attr];
            }
        }
        return target;
    }

2. After the preparations are completed, start encapsulating ajax

   function ajax(options){
    
    
   //首先定义一个默认的对象存储默认的请求信息
        var _default = {
    
    
        //请求方式
            type:"GET",
            //请求路径
            url:"",
            //请求数据 此处除了text 外可以json对象
            datatype:"text",
            //请求的数据
            data:null,
            //成功则执行
            success:function(){
    
    },
            //失败则执行
            error:function(){
    
    },
            //完成则执行
            complete:function(){
    
    },
            //是否改变回调函数的this指向
            context:null
        }
        //首先利用刚才封装的合并对象方法 把的实参覆盖原来定义的默认对象
        options = assign(_default,options);
        //把请求方式统一小写/大写 方便后面判断
        options.type = options.type.toLowerCase();
		//判断是否存在改变指针的对象 存在则利用bind改变指针指向
        if(isObject(options.context)){
    
    
            var calllist = ["success","error","complete"];
            calllist.forEach(function(item){
    
    
                options[item] = options[item].bind(options.context);
            })
        }
		//获取xhr 此处用到了兼容性写法
        var xhr = null;
        if(typeof XMLHttpRequest === "function"){
    
    
            xhr = new XMLHttpRequest();
        }else{
    
    
            xhr = new ActiveXObject("Microsoft.XMLHttp");
        }
        //判定请求方式 因为get请求的url中附带数据 post请求的date中携带数据 所以根据需求修改对应的数据
        if(options.type === "get"){
    
    
            options.url = toUrlData(options.data,options.url,options.type)
        }
        if(options.type === "post"){
    
    
            options.data = toUrlData(options.data,options.url,options.type)
        }
        //开放连接
        xhr.open(options.type,options.url,true);
        // 如果为post要修改请求头
        options.type === "post" ? xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded") : "";
        //传送数据 get的话传送null即可
        xhr.send(options.type === "post"?options.data:null);
        xhr.onreadystatechange = function(){
    
    
            if(xhr.readyState === 4){
    
    
            //当readyState为4执行连接完成方法
                options.complete();
                //当status为200-299执行连接成功方法
                if( /^2\d{
    
    2}/.test(xhr.status) ){
    
    
                    try{
    
    
                    //当用户请求的对象为json时 有可能会转化错误 此处用抛异常 解决该问题
                        var res = options.datatype === "json"?JSON.parse(xhr.responseText):xhr.responseText;
                        options.success(res);
                    }catch(e){
    
    
                        options.error(e);
                    }
                }else{
    
    
                //否则执行连接失败方法
                    options.error(xhr.status);
                }
            }
        }
    }

3. Summary

1. Declare the default object and change the object content with new arguments
2. Get xhr
3. Change the url and data according to the request method
4. Open connections
5. Modify the request header when posting
6.Send data
7. Determine the connection status and execute the corresponding method with just one ajax.

Guess you like

Origin blog.csdn.net/qq_41383900/article/details/105164725