等待所有 ajax 调用结束,然后再显示 SweetAlert2 Toastr mixin



我正在使用下面的代码在ajax请求后显示通知


const Toast = Swal.mixin({ toast: true, position: 'top-end', showConfirmButton: false, timer: 3000 });
//ajax call
$.ajax({
.....
success: function(response){
reloadpanel1(response.id);   //another ajax call
reloadpanel2(response.id);   //another ajax call
Toast.fire({
type: 'success',
title: response.message,
customClass: { popup: 'adjust' }
})
}
})

问题是通知甚至在reloadpanel1reloadpanel2完成请求之前弹出。 有没有办法让Toastr在所有 ajax 调用尚未完成时不会触发?

编辑:

$(document).ajaxStart()/.ajaxStop()不会这样做,因为通知消息取决于 JSONresponse.message

必须尝试异步等待

const Toast = Swal.mixin({ toast: true, position: 'top-end', showConfirmButton: false, timer: 3000 });
//ajax call
$.ajax({
.....
success: async function(response){
await reloadpanel1();   //another ajax call
await reloadpanel2();   //another ajax call
Toast.fire({
type: 'success',
title: response.message,
customClass: { popup: 'adjust' }
})
}
})

使用 jquery when 函数为我的问题找到了一个简洁的解决方案

const Toast = Swal.mixin({ toast: true, position: 'top-end', showConfirmButton: false, timer: 3000 });
//ajax call
$.ajax({
.....
success: function(response){
$.when(reloadpanel1(), reloadpanel2()).done(function(){
Toast.fire({
type: 'success',
title: response.message,
customClass: { popup: 'adjust' }
})
})
}
})

最新更新