2017-05-31 195 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 
     } 
    }) 
});