Skip to content

Instantly share code, notes, and snippets.

@interjc
Last active February 3, 2016 01:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save interjc/53f574fc6d7c67b98046 to your computer and use it in GitHub Desktop.
Save interjc/53f574fc6d7c67b98046 to your computer and use it in GitHub Desktop.
Promise XHR
'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);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment