0%

基于 ES6 Promise 的 AJAX 简单封装

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

'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);
});

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