微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

js封装ajax

//封装ajax
        function ajax(obj) {
            //创建xhr对象;
            var xhr = new XMLHttpRequest();
            //后面随机数防止浏览器缓存
            obj.url = obj.url + "?rand=" + Math.random();
            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);
            if (obj.method == 'POST') {
                xhr.send(obj.data);
            } else {
                xhr.send();
            }
            //同步调用
            if (!obj.async) {
                callback();
            }

            function callback() {
                try {
                    var res = JSON.parse(xhr.response)
                } catch (e) {
                    console.error(e)
                }
                if (xhr.status == 200) {
                    obj.success && obj.success(res);
                } else {
                    obj.error && obj.error(res);
                }
            }
        }


            ajax({
                method: 'post',
                url: 'test.test.test',
                data: formData,
                async: true,
                success: function(res) {
                      
                },
                error: function(e) {
                 
                },
            });

  

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐