使用Jquery $ when进行条件异步调用

时间:2014-11-14 05:13:48

标签: javascript jquery ajax promise .when

我需要进行两次异步(仅在某些条件为真的情况下才需要进行第二次调用)调用,并且当两次调用都返回数据时,我需要进行另一次调用。为此我决定使用jquery $。

在我进行第二次Ajax调用之前,我需要检查一些条件。如果它是真的,那么我需要进行第二次ajax调用,否则,不需要进行第二次ajax调用。

这是伪代码

 $.when($.get(url, function (result, status, xhr) {
        myresult = result;
    })),
    (
        //If XYZ === 10
          //Make second Ajax call only if condition is true

    ).then(function (r1, r2) {
        //DO something

     });

我怎样才能做到这一点?使用Jquery或任何其他库??

3 个答案:

答案 0 :(得分:0)

两个ajax请求成功后执行一个函数。

$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) {

  //if both the calls are sucess then only you can reach here.
  //  inside this you can make your third ajax call.

  }
});

答案 1 :(得分:0)

var first = $.ajax(...);
var second = (condition) ? $.ajax(...) : $.Deferred().resolve(); // ajax only on condition

$.when(first, second).then(function(res1, res2){
    // work with res1 and res2, res2 is undefined if no call was made
});

答案 2 :(得分:0)

您可以使用三元运算符进行第二次ajax调用。如果condition为false,则传递null值作为$.when的第二个参数。

这是伪代码

$.when(
    //first ajax call ,
    (XYZ===10) ? //second ajax call 
               : null
       ).then(function (r1, r2) {
        //DO something

     });

希望它有所帮助。

演示: - jsfiddle.net/NF2jz/5721(尝试a = 0和a = 1)

相关问题