这是我的代码
$.each(result, function (index, value) {
if (value.name != null) {
$.ajax({
// myApi call code
});
}
// I only want reach here after api call finish
if (value.flag) {}
});
在循环内部有两个条件,一个是检查里面的name != null
和api调用,另一个是value.flag
。我只想在api调用完成后达到第二个条件。
发布于 2018-08-17 01:14:58
当ajax请求完成时,您可以使用done函数
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$( this ).addClass( "done" );
});
发布于 2018-08-17 01:18:45
看看文档:https://api.jquery.com/jquery.ajax
我认为您正在寻找的是以下内容:
$.ajax({
// options
})
.done(function (response) {
// do something with the response
})
.fail(function (response) {
// handle the error case
})
.always(function (response) {
// do something always at the end of the sequence
})
考虑到这一点,您必须将value.flag
检查转移到回调:
$.each(result, function (index, value) {
if (value.name != null) {
$.ajax({ /* options */ })
.done(function (response) {
// this check will happen only if the request succeeds
if (value.flag) {}
})
.fail(function (response) {
// this check will happen only if the request fails
if (value.flag) {}
})
.always(function (response) {
// this check will always happen after the request
if (value.flag) {}
})
}
)};
https://stackoverflow.com/questions/51882223
复制相似问题