2016-10-15 201 views
0

如何在新線程中調用ajax請求或任何簡單的函數?如何異步調用ajax調用並顯示加載器直到完成?

我知道async: false但我的代碼有這樣的結構:在一些項目

1.USER點擊,這火click事件
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); 

我目前的代碼工作,但導致網絡凍結,直到數據不下載beaouse我有asyn: false,但我不知道如何異步解決它

最適合我的解決方案是調用這個凍結並顯示加載gif直到完成。

回答

0

那麼在同步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

+0

謝謝:)作品 –

0

變化async:falseasync:true所有Ajax調用,在你的函數,你初始化myData並打電話給你想在所有數據中籤功能加載在最後調用Ajax調用的函數(只是開始顯示加載GIF在myData.s2 = s2

相關問題