开发者

Two AJAX calls: upon success render the content to the browser at the same time

I got problem with two AJAX calls. I'm calling it from a jquery object. I want upon success for the AJAX call who get the content first to wait to render it until the second AJAX request also recieve开发者_开发技巧s the content.


You could do something like this:

(function() {
   var executedAmount = 0;
   var datas = {};
   //Ajax call 1:
   $.ajax({
      'success': function(data) {
          executedAmount++;
          datas[0] = data;
          callBack();
      }
   });
   //Ajax call 2:
   $.ajax({
      'success': function(data2) {
          executedAmount++;
          datas[1] = data2;
          callBack();
      }
   });
   function callBack() {
      if (executedAmount == 2) {
          //Do something with datas here
      }
   }
})();


if you can use jQuery 1.5, then this would answer your problem.

Introducing $.when()

Example: Execute a function after two ajax requests are successful. (See the jQuery.ajax() documentation for a complete description of success and error cases for an ajax request).

$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1,  a2){
    /* a1 and a2 are arguments resolved for the 
        page1 and page2 ajax requests, respectively */
   var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
   if ( /Whip It/.test(jqXHR.responseText) ) {
      alert("First page has 'Whip It' somewhere.");
   }
});


Just to add to the above answer, you could just measure the length of datas instead of having a separate variable.


what if you use this function

$(document).ready(function(){
    $('selector').jaxStop(function() {
      //Do some thing
         WhenAjaxEnds();
    });
});

function  WhenAjaxEnds(){
  //do something here ....
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜