【问题标题】:Wait for all ajax calls to end before showing SweetAlert2 Toastr mixin在显示 SweetAlert2 Toastr mixin 之前等待所有 ajax 调用结束
【发布时间】:2019-09-27 05:10:30
【问题描述】:

我正在使用下面的代码在 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 完成他们的请求之前弹出。 如果所有 ajax 调用尚未完成,有没有办法让 Toastr 不会触发?

编辑:

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

【问题讨论】:

    标签: javascript ajax sweetalert sweetalert2


    【解决方案1】:

    必须尝试异步等待

    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' }
            })
        }
    })
    

    【讨论】:

    • 对不起。但这似乎不起作用。 reloadpanel1reloadpanel2 是包含 ajax 调用的函数。
    • 那么你必须在 reloadpanel1(); 中尝试 Promises;和 reloadpanel2();
    • function reloadpanel1 { return new Promise(function(resolve, reject) { resolve('foo'); };
    • 你能给我一个更详细的例子吗?谢谢
    • function reloadpanel1(id) { return new Promise(function(resolve, reject) { var data = { id: id} $.ajax({ url: '/main/upto/process', 输入: 'post', 缓存: false, data: data, 成功: function (res) { $('#processingpanel').html(res); resolve(res) } }) }); }
    【解决方案2】:

    使用 jquery when function 为我的问题找到了一个巧妙的解决方案

    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' }
                })
            })
        }
    })
    

    【讨论】:

      猜你喜欢
      • 2011-02-07
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      • 2021-09-14
      相关资源
      最近更新 更多