原生ajax请求封装一波

  现在的前端,大项目用框架(VUE、REACT、ANGULAR),小页面用原生,不过原生ajax好像不是很多人用,甚至不如jquery。也许是因为很多人觉得原生的XMLHttpRequest太麻烦了吧,不过我个人不喜欢因为某个框架的一点点功能就在项目中引入整个框架,浪费资源...!所以还是自己写吧

 1 (function(app) {
 2     'use strict';
 3 
 4     app.http = {
 5         get: get,
 6         post: post
 7     };
 8 
 9     function get(url) {
10         return send('GET', url);
11     }
12 
13     function post(url, data) {
14         return send('POST', url, data || {});
15     }
16 
17     function send(type, url, data) {
18         var http = initHttp(),success = [], fail = [], over = [], ch = [], params = [];
19         //这里注意,我使用的是表单提交:Content-Type:application/x-www-form-urlencoded,有的人可能用json之类的,写法会不一样,根据自己的项目来,一个项目固定一种交互规则是很有必要的,所以不推荐都写在一起加参数区分不同的规则
20         var formData = new FormData();
21         if(data) {
22             for(var d in data) {
23                 if(typeof data[d] === 'object' && data[d].toString() === '[object Blob]') {
24                     formData.append(d, data[d], data[d].name);
25                 } else {
26                     formData.append(d, data[d]);
27                 }
28             }
29         }
30         try {
31             http.open(type, url);
32             http.setRequestHeader("If-Modified-Since","0");
33             http.setRequestHeader("Cache-Control","no-cache");
34             http.onreadystatechange = function() {
35                 if((http.readyState === 4) && (http.status === 200)) {
36                     var response = JSON.parse(http.responseText);
37                     success.map(function(s) {s && s(response);});
38                     over.map(function(o) {o && o();});
39                 } else if(http.readyState === 4) {
40                     fail.map(function(f) {f && f(http);});
41                     ch.map(function(c) {c && c(http);});
42                     over.map(function(o) {o && o();});
43                 }
44             };
45             http.send(formData);
46         } catch(e) {
47             ch.map(function(c) {c && c(e);});
48             over.map(function(o) {o && o(e);});
49         }
50         return {
51             then: function(a, b) {
52                 success.push(a);
53                 fail.push(a);
54                 return this;
55             },
56             success: function(a) {
57                 success.push(a);
58                 return this;
59             },
60             fail: function(b) {
61                 fail.push(b);
62                 return this;
63             },
64             catch: function(d) {
65                 ch.push(d);
66                 return this;
67             },
68             finally: function(c) {
69                 over.push(c);
70                 return this;
71             }
72         }
73     }
74 
75     function initHttp() {
76         var xmlHttp;
77         if(window.ActiveXObject) {
78             xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
79         } else if(window.XMLHttpRequest) {
80             xmlHttp = new XMLHttpRequest();
81         }
82         return xmlHttp;
83     }
84 })(window);

使用方法的话,因为注册到了window下:

1 http.get(url).then(function(res) {
2    console.log('success:', res); 
3 }).catch(function(err) {
4    console.log('error:', err); 
5 }).finally(function() {
6    console.log('finally');     
7 })

就行了,这里默认返回JSON,如果不是的话记得修改36行部分代码哦,想要put、delete方法的同学参考post自行添加哦

posted @ 2021-02-20 14:03  lonis  阅读(71)  评论(0)    收藏  举报