Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jqueryajax一个接一个_Jquery_Ajax - Fatal编程技术网

jqueryajax一个接一个

jqueryajax一个接一个,jquery,ajax,Jquery,Ajax,我试图一个接一个地运行两个ajax请求。因此,我可以使用ajax成功函数: $.ajax({ ... success: function() { //here the second ajax request } }); 问题是,第一个ajax请求仅在条件为true时执行。所以我的代码看起来像: if($cond) { $.ajax({ ... }); } $.ajax({ ... }); 如何逐个运行这些请求?或

我试图一个接一个地运行两个ajax请求。因此,我可以使用ajax成功函数:

$.ajax({
    ...
    success: function() {
        //here the second ajax request
    }
});
问题是,第一个ajax请求仅在条件为true时执行。所以我的代码看起来像:

if($cond) {
    $.ajax({
        ...
    });
}
$.ajax({
    ...
});
如何逐个运行这些请求?或者第二个只在第一个完成时执行是标准的吗?

jQuery 1.5引入并返回一个:

$.ajax({
   //...
}).then(function() {
    $.ajax({
        //...
    });
});
参考:

更新:

在您的情况下,您可以这样做:

var deferred = jQuery.Deferred();
deferred.resolve();  // <- I think you need this here but I'm not sure.

if($cond) {
    deferred = $.ajax({
        ...
    });
}
deferred.then(function() {
    $.ajax({
      //...
    });
});
jQuery 1.5已引入,正在返回一个:

$.ajax({
   //...
}).then(function() {
    $.ajax({
        //...
    });
});
参考:

更新:

在您的情况下,您可以这样做:

var deferred = jQuery.Deferred();
deferred.resolve();  // <- I think you need this here but I'm not sure.

if($cond) {
    deferred = $.ajax({
        ...
    });
}
deferred.then(function() {
    $.ajax({
      //...
    });
});

这将不起作用,因为第一个ajax请求处于$cond条件下,而第二个不处于$cond条件下。但是第二个请求仅在第一个请求执行时起作用。看来最好的解决办法是使第一个请求同步。@groh:你看到我的更新了吗?我添加了延迟。解决;。。。。还是什么不清楚?它应该是这样工作的。@groh:太好了:编码快乐!这将不起作用,因为第一个ajax请求处于$cond条件下,而第二个不处于$cond条件下。但是第二个请求仅在第一个请求执行时起作用。看来最好的解决办法是使第一个请求同步。@groh:你看到我的更新了吗?我添加了延迟。解决;。。。。还是什么不清楚?它应该是这样工作的。@groh:太好了:编码快乐!