繁体   English   中英

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

[英]Making conditional Async calls using Jquery $when

我需要进行两个异步( 仅当某些条件为true时才需要进行第二次调用 )调用,并且当两个调用都返回数据时,我需要进行另一个调用。 为此,我决定使用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或任何其他库?

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

  }
});
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
});

您可以使用三元运算符进行第二个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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM