///////////////////////
// 定义ajax-promise.js
///////////////////////
var AjaxPromise = function(url, method, header, data) {
return new Promise(function(resolve, reject) {
var xhr = createXHR();
xhr.open(method, url, true);
for (var key in header) {
xhr.setRequestHeader(key, header[key]);
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
resolve(xhr.responseText);
} else {
reject('请求失败');
}
}
};
xhr.send(data);
});
};
///////////////////////
// 使用
///////////////////////
<script src="../promise/libs/promise.js"></script>
<script src="libs/ajax-promise.js"></script>
AjaxPromise('https://cn.vuejs.org/images/logo.png', 'GET', {}, {})
.then(function (res) {
console.log(res);
}).catch(function (err) {
console.log(err);
});