【问题标题】:Making conditional Async calls using Jquery $when使用 Jquery $when 进行条件异步调用
【发布时间】:2015-01-11 10:51:18
【问题描述】:

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

在我进行第二次 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 或任何其他库??

【问题讨论】:

  • 您的描述似乎自相矛盾。首先,“我需要进行两个异步调用,并且当两个调用都返回数据时,我需要进行另一个调用”,然后您说第二个调用仅基于第一个调用的结果进行。你能澄清你在问什么吗?顺便说一句,答案是肯定的——你可以使用 jQuery 来实现。
  • @Colin:只有在某些条件为真时,我才需要进行第二次 Ajax 调用。如果我要打第二个电话,那么只有当我从两个电话中获取数据时,我才应该打最后一个电话。

标签: javascript jquery ajax promise .when


【解决方案1】:

两个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.

  }
});

【讨论】:

  • 在这种情况下,我不需要使用$when。我可以进行 Ajax 调用,如果成功,我可以根据需要进行第二次 ajax 调用(基于某些条件)。
【解决方案2】:
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
});

【讨论】:

    【解决方案3】:

    您可以使用三元运算符进行第二次 ajax 调用。如果条件为 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)

    【讨论】:

    • @VladislavDimitrov 看到这个演示。 jsfiddle.net/NF2jz/5721 将 a 的值更改为 1,它将根据第二个请求更新文本。
    猜你喜欢
    • 1970-01-01
    • 2017-03-17
    • 2020-08-28
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多