用异步回调嵌套,在200成功的逻辑里面继续触发对应的回调函数,下面就是封装ajax方法,触发ajax方法时候接受一个回调函数,在成功之后触发对应的回调函数,回调函数里面可以继续触发对应ajax方法:
function ajax(callback) {
var xhr = new XMLHttpRequest();
xhr.open('get', 'aabb.php', true);
xhr.send(null);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
callback(xhr.responseText);
console.log(xhr.responseText);
}
}
}
}
ajax(function (data) {
ajax(function (data) {
})
})
或者使用Promise封装,配合then或者async或者await均可:
function ajax(callback) {
return new Promise(function (resolve) {
var xhr = new XMLHttpRequest();
xhr.open('get', 'aabb.php', true);
xhr.send(null);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
resolve(xhr.responseText);
console.log(xhr.responseText);
}
}
}
})
}
ajax().then(function () {
// do somg thing
ajax().then(function () {
// do somg thing
})
})