function ajax(url, fnSucc, fnFail) {
var oAjax = new XMLHttpRequest();
oAjax.open('GET', url, true);
oAjax.send();
oAjax.onload = function () {
if (oAjax.readyState == 4 && oAjax.status == 200) {
fnSucc(oAjax.responseText)
} else {
fnFail(oAjax.status);
}
};
}
window.onload = function () {
let oBtn = document.getElementById('btn1');
oBtn.onclick = function () {
ajax('a.txt', function (str) {
alert(str);
}, function (str) {
alert(str);
});
};
};
promise异步封装例子
function ajax(url, fnSucc, fnFail) {
var oAjax = new XMLHttpRequest();
oAjax.open('GET', url, true);
oAjax.send();
oAjax.onload = function () {
if (oAjax.readyState == 4 && oAjax.status == 200) {
fnSucc(oAjax.responseText)
} else {
fnFail(oAjax.status);
}
};
}
window.onload = function () {
let oBtn = document.getElementById('btn1');
let oBox = document.getElementById('box1');
oBtn.onclick = function () {
let p1 = new Promise(function (resolve, reject) {
ajax('a.txt', function (str) {
resolve(str);
}, function (str) {
reject(str);
});
});
p1.then(function (str) {
oBox.innerHTML = str;
}, function (str) {
oBox.innerHTML = str;
});
};
};
网友评论