以串行方式发布多个Ajax帖子 [英] Multiple Ajax posts in a serial manner

查看:64
本文介绍了以串行方式发布多个Ajax帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现多个ajax发布请求.假设有3个帖子.然后,第二个帖子取决于第一个帖子的结果,而第三个帖子则取决于从第二个帖子收到的结果.

I want to implement multiple ajax post requests. Suppose there are 3 posts. Then the 2nd post is dependent on the result from the first and the third post is dependedent on the result received from the 2nd post.

如何放置第二个ajax post方法.应该在成功处理程序中完成吗 jQuery.ajax({ 类型:发布", dataType:"json", url:ajaxurl, 数据:form_data,

How do I place the 2nd ajax post method. Should it be done in the success handler jQuery.ajax({ type : "post", dataType : "json", url : ajaxurl, data : form_data,

   async: false,  
   success: function(response) {
              //2nd ajax post call to be placed here?

      } 
  }       

})   

//或应该在

我已经看到一些人也在使用jQuery.when(),但是我不确定是否可以使用它. 从这里开始,我将不得不检查条件何时出现3次.

I have seen some people also using jQuery.when() but I am not sure whether I could use that. Since here I will have to check for when condition 3 times.

预先感谢.

推荐答案

像这样吗?

来自 https://api.jquery.com/jQuery.when/

$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) {
  // a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively.
  // Each argument is an array with the following structure: [ data, statusText, jqXHR ]
  var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It"
  if ( /Whip It/.test( data ) ) {
    alert( "We got what we came for!" );
  }
});

a1,a2是从各种回调返回的结果吗? (但是,这将执行三个回调(异步),但返回所有三个回调的结果)

a1, a2 being the results returned from the various callbacks? (This will however execute your three callbacks (async), but return the results of all three)

否则,如果您有一个从request1到request2的依赖项,则可以执行以下操作: https://api.jquery.com/jQuery.ajax/

Otherwise if you've got a dependency from request1 to request2 you can do something like this https://api.jquery.com/jQuery.ajax/

$.ajax("page1.php").done(function(a1) {
    if (a1 == "something") { // if 2nd call dependent on results from 1st
        $.ajax("page2.php").done(function(a2) {
        }).fail(function() {
            // handle with grace
        });
    }
}).fail(function() {
    // handle with grace
});

这篇关于以串行方式发布多个Ajax帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆