js封装ajax

//封装ajax
        function ajax(obj) {
            //创建xhr对象;
            var xhr = new XMLHttpRequest();
            obj.method = obj.method.toUpperCase();
            //异步调用
            if (obj.async) {
                //监听响应状态
                xhr.onreadystatechange = function() {
                    if (xhr.readyState == 4) {
                        callback();
                    }
                };
            }

            //启动HTTP请求
            xhr.open(obj.method, obj.url, obj.async);
            xhr.responseType = "json";
            if (obj.method === 'POST') {
                if (obj.isForm) {
                    xhr.send(obj.data);
                } else {
                    xhr.setRequestHeader('Content-Type', 'application/json');
                    xhr.send(JSON.stringify(obj.data));
                }
            } else if (obj.method === 'GET') {
                xhr.send();
            }
            //同步调用
            if (!obj.async) {
                callback();
            }

            function callback() {
                if (xhr.status == 200) {
                    obj.success && obj.success(xhr.response);
                } else {
                    obj.error && obj.error(xhr.response);
                }
            }
        }

  

原文地址:https://www.cnblogs.com/ckAng/p/11022118.html