如何在两个ajax请求成功后执行一个函数?

时间:2014-08-14 10:11:01

标签: jquery ajax

Function1()
{
    //Make Ajax Request
    $.ajax({
    url:url1,
    success:function abc(){
    }
})
...
}

Function2(){
//Make Ajax Request
$.ajax({
   url:url2,
   success:function cde(){
   }
})
...
}

Function3(){
//This function should execute after function 1 and 2 successfull.
...
}

注意:功能3应仅在"成功"之后执行。功能abc和"成功" function cde完成执行。

请做必要的

3 个答案:

答案 0 :(得分:1)

您可以使用jQuery.when( deferreds ) - 请参阅http://api.jquery.com/jquery.when/

代码段 -

$(function() {
    $.when($.ajax("response1.json"), $.ajax("response2.json")).then(function(response1, response2) {
        console.log(response1, response2);
        $("#message").html("say hi to " + response1[0].name + " and " + response2[0].name);
    });

});

在plunkr演示 - http://plnkr.co/edit/abPYPUQ49G0MhrcED31Z?p=preview

答案 1 :(得分:0)

你可以试试,

var flagFunc1=false;
var flagFunc2=false;

Function1()
{
    //Make Ajax Request
    $.ajax({
      url:url1,
       success:function abc(){  dummyFunction(1); }
    });
    ...
}    
Function2(){
   //Make Ajax Request
   $.ajax({
      url:url2,
      success:function cde(){ dummyFunction(2); }
   })
   ...
}
function dummyFunction(f){
   if(f==1){ // function 1 success
       flagFunc1=true;
   } else if(f==2) { // function 2 success
       flagFunc2=true;
   }
   if(flagFunc1==true && flagFunc2==true){
       Function3();//finally call function 3
   }
}
Function3(){
  //This function should execute after function 1 and 2 successfull.
  ...
}

答案 2 :(得分:0)

var temp =0;

 Function1()
    {
        //Make Ajax Request
        $.ajax({
        url:url1,
        success:function abc(){
         temp++;
          if(temp==2)
             Function3() //call function here
        }
    })
    ...
    }

    Function2(){
    //Make Ajax Request
    $.ajax({
       url:url2,
       success:function cde(){
     temp++;
    if(temp==2)
      Function3() //call function here
       }
    })
    ...
    }

    Function3(){
    //This function should execute after function 1 and 2 successfull.
    ...
    }