2017-05-31 158 views
0

我有兩個請求,一個是加載圖像(後端服務器會花費很多時間),另一個是ajax。 我要像以下:如何處理多個異步請求?

$.when(
    [do image load] 
    [do ajax] 
).then(
    alert('all complete') 
) 

然而,$。當然後使用多個Ajax請求,如何處理與Ajax和圖像加載

+1

* 「然而,$。當再使用多個AJAX請求」 * - 他們不是* *專門爲Ajax請求,他們的承諾(或jQuery的deferreds )。您可以創建自己的承諾,在圖像加載並將該承諾傳遞給'$ .when()'時解析。 – nnnnnn

回答

0
$.when(
    $.get("/ajax/", function(response) { 
    //process ajax 
    }), 
    $.get("/assets/image.png", function(image) { 
    // process image 
    }), 
).then(function() { 
    // All is ready now, so... 
    alert('all complete') 
}); 
+0

謝謝你的回覆,我會試一試 – sknight

0

我想建議Gauri的imgLoad插件從jQuery callback on image load (even when the image is cached)

/** 
* Trigger a callback when 'this' image is loaded: 
* @param {Function} callback 
*/ 
(function($){ 
    $.fn.imgLoad = function(callback) { 
     return this.each(function() { 
      if (callback) { 
       if (this.complete || /*for IE 10-*/ $(this).height() > 0) { 
        callback.apply(this); 
       } 
       else { 
        $(this).on('load', function(){ 
         callback.apply(this); 
        }); 
       } 
      } 
     }); 
    }; 
})(jQuery); 

用法,

$('#img-if').imgLoad(function(){ 
    // inside the image complete callback 
    $.ajax({ 
     .... 
     success:function(response){ 
      // final code to be executed here 
     } 
    }) 
});