通过ES6实现的Ajax类

个人学习用途而已,仅供参考。

 1 class Ajax  {
 2     constructor(xhr) {
 3         xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
 4         this.xhr = xhr;
 5     }
 6 
 7     send(method, url, async, callback, data) {
 8         let xhr = this.xhr;
 9 
10         xhr.onreadystatechange = () => {
11             // readyState: 0: init, 1: connect has set up, 2: recive request, 3: request.. , 4: request end, send response
12             if (xhr.readyState === 4 && xhr.status === 200) {
13                 // status: 200: OK,  404: Not Found Page
14                 callback(xhr.responseText);
15             }
16         };
17 
18         xhr.open(method, url, async);   
19         xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
20         xhr.send(data);
21     }
22 }

Promise增强版:

 1 class Ajax  {
 2     constructor(xhr) {
 3         xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
 4         this.xhr = xhr;
 5     }
 6 
 7     send(options) {
 8 
 9         let xhr = this.xhr;
10 
11         let opt = {
12             type: options.type || 'get',
13             url: options.url || '',
14             async: options.async || true,
15             dataType: options.dataType || 'json',
16             questring: options.questring || ''
17         };
18 
19         return new Promise((resolve, reject) => {
20 
21             xhr.open(opt.type, opt.url, opt.async);
22 
23             xhr.onreadystatechange = () => {
24                 // readyState: 0: init, 1: connect has set up, 2: recive request, 3: request.. , 4: request end, send response
25                 if (xhr.readyState === 4) {
26                     if (xhr.status === 200) {
27                         // status: 200: OK,  404: Not Found Page
28                         if (opt.dataType === 'json') {
29                             const data = JSON.parse(xhr.responseText);
30                             resolve(data);
31                         }
32                     } else {
33                         reject(new Error(xhr.status || 'Server is fail.'));
34                     }
35                 }
36             };
37 
38             xhr.onerror = () => {
39                 reject(new Error(xhr.status || 'Server is fail.'));
40             }
41 
42             xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
43             xhr.send(opt.questring);
44 
45         });
46     }
47 }

 

 

点击获取源码

转载于:https://www.cnblogs.com/tim100/p/6807177.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值