0%

基于 ES6 Promise 的 AJAX 简单封装

基于 Promise 的 ajax 请求,可以实现链式调用,使代码结构更清晰,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
'use strict';
// 函数封装
var handleAjax = function handleAjax() {
var options = arguments.length <= 0 || arguments\[0\] === undefined ? {} : arguments\[0\],
opt = {
url: options.url || '',
data: options.data || 't=' + new Date().getTime(),
type: options.type || 'get',
dataType: options.dataType || 'json',
cache: options.cache || false,
async: options.async || true,
context: options.context || document.body,
beforeSend: options.beforeSend || undefined
};
return new Promise(function (resolve, reject) {
var req = new XMLHttpRequest();
if (typeof opt.beforeSend === 'function') {
opt.beforeSend();
}
req.open(opt.type, opt.url, opt.async);
req.onload = function () {
if (req.status === 200) {
var data = req.responseText;
if (opt.dataType === 'json') {
data = JSON.parse(data);
}
resolve(data);
} else {
reject(new Error(req.statusText || 'You can\\'t do this.'));
}
};
req.onerror = function () {
reject(new Error(req.statusText || 'Server is down.'));
};
req.send();
});
};
// 调用函数
var options = {
url: 'http://httpbin.org/get'
};
handleAjax(options).then(function (data) {
console.log(data);
})\['catch'\](function (error) {
console.log(error);
});

预览效果 | 源码 | 参考资料

欢迎关注我的其它发布渠道