如何使用 ajax 异步调用并显示加载程序直到完成?

How to function with ajax calls asynchronously and display loader until done?

如何在新线程中调用 ajax 请求或任何简单的函数?

我知道 async: false 但我的代码有这样的结构:

1.user点击某项,触发点击事件
2.in事件我调用这个函数

var myData= {};
$.ajax({
        type: "GET",
        url: "...",
        contentType: "application/json; charset=utf-8",
        async: false,
        cache: false,
        dataType: "json",
        success: function (s0) {
            myData.s0= s0;


            $.ajax({
                type: "GET",
                url: "sss",
                contentType: "application/json; charset=utf-8",
                async: false,
                cache: false,
                dataType: "json",
                success: function (s1) {
                    myData.s1 = s1;

                    $.ajax({
                        type: "GET",
                        url: "...",
                        contentType: "application/json; charset=utf-8",
                        async: false,
                        cache: false,
                        dataType: "json",
                        success: function (s2) {
                            myData.s2= s2;
                        }
                    });
                }
            });
        }
    });

    // I need call this function when all ajax are done.
    myFunc(myData);

我当前的代码有效,但导致网络冻结,直到数据未下载,因为我有 asyn: false 但我不知道如何异步解决它

我的最佳解决方案是调用此冻结并显示加载 gif 直到完成。

在所有 ajax 调用中将 async:false 更改为 async:true,在您初始化 myData 并调用您想要的函数的函数开始处显示加载 gif在最后一次 ajax 调用的成功函数中加载所有数据时调用(就在 myData.s2 = s2 之后)

好吧,在同步 AJAX 期间没有解决 UI 冻结问题,因此您可能想尝试网络工作者,但它有自己的警告。我建议您使用 jquery 承诺这样你就不需要定义单独的成功,错误回调。承诺是 保证 产生所以在链的末尾你将在 myData 中有值或没有但它永远不会挂断电话

//show loader
$.ajax({
        type: "GET",
        url: "...",
        contentType: "application/json; charset=utf-8",
        async: false,
        cache: false,
        dataType: "json",
}).then(function( s0, textStatus, jqXHR ){ 
         myData.s0= s0;
         return  $.ajax( {
         type: "GET",
         url: "sss",
         async: false,
         cache: false,
         dataType: "json"} );
 }).then(function( s1, textStatus, jqXHR ) { 
          myData.s1 = s1;
          $.ajax( {
          type: "GET",
          url: "...",
          async: false,
          cache: false,
          dataType: "json"});  
}).then(function( s2, textStatus, jqXHR ) {
          myData.s2= s2;
          //hide loader
})

Read more