简体   繁体   English

jQuery多个AJAX调用

[英]JQuery Multiple AJAX call

Please refer the code below, I already set both of the ajax as async : false. 请参考下面的代码,我已经将两个ajax都设置为async:false。 I found out that when the function calling doUpdate2ndAJAX(), the program start executing $(".search").click(); 我发现,当函数调用doUpdate2ndAJAX()时,程序开始执行$(“。search”)。click();。 even though doUpdate2ndAJAX() not yet finish executing. 即使doUpdate2ndAJAX()尚未完成执行。

In short current situation: 1. doUpdate2ndAJAX() execute 2. doUpdate2ndAJAX() not yet finish, start execute $(".search").click() 3. doUpdate2ndAJAX() Finish execute and response back 在当前情况下:1. doUpdate2ndAJAX()执行2. doUpdate2ndAJAX()尚未完成,开始执行$(“。search”)。click()3. doUpdate2ndAJAX()完成执行并返回响应

May I know how can I make it as 1. doUpdate2ndAJAX() execute 2. doUpdate2ndAJAX() Finish execute and response back 3. call $(".search").click(); 我可以知道如何做到这一点吗?1. doUpdate2ndAJAX()执行2. doUpdate2ndAJAX()完成执行并返回响应3.调用$(“。search”)。click();。

[ Execute in sequence order ] [按顺序执行]

Thanks. 谢谢。 -fsloke -fsloke

firstCalled: function() {
             $.ajax({                          
            url: "XXX",
            async: false,
            success: function(response) {

                        doUpdate2ndAJAX();

                        $(".search").click();

                        }
           });
}               

function  doUpdate2ndAJAX(){
              $.ajax({                         
            url: "YYY",
            async: false,
            success: function(response) {
                            // UPDATE SOMETHING
                        }
               });
              return false;
}

Use Deferred objects, those are objects to manipulate async calls, you can solve : 使用Deferred对象,这些是操纵异步调用的对象,可以解决:

$.when($.ajax("/page1.php"), $.ajax("/page2.php"))
  .then(myFunc, myFailure);

This way myFunc executes after the 2 ajax calls are made, and myFailure if either one has an error. 这样,myFunc会在执行2个ajax调用后执行,如果其中一个有错误,则执行myFailure。

You can read more about it in the jquery official documentation: JQuery Deferred Object 您可以在jquery官方文档中了解有关它的更多信息: JQuery Deferred Object

You should make the AJAX calls asynchronous, and call $(".search").click(); 您应该使AJAX调用异步,然后调用$(".search").click(); in the success callback for the second request. 在第二个请求的success回调中。

Depending on your structure, you may want to add a parameter to doUpdate2ndAJAX which tells it whether to call $(".search").click(); 根据您的结构,您可能想要向doUpdate2ndAJAX添加参数,该参数告诉它是否调用$(".search").click(); .
Alternatively, you can add a callback parameter. 或者,您可以添加一个回调参数。

I suggest to use the "complete" callback to invoke the $(".search").click(). 我建议使用“ complete”回调来调用$(“。search”)。click()。

You can see the differences between success and complete callbacks here: http://api.jquery.com/jQuery.ajax/ 您可以在此处查看成功和完整回调之间的区别: http : //api.jquery.com/jQuery.ajax/

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

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