简体   繁体   中英

JQuery Multiple AJAX call

Please refer the code below, I already set both of the ajax as async : false. I found out that when the function calling doUpdate2ndAJAX(), the program start executing $(".search").click(); even though doUpdate2ndAJAX() not yet finish executing.

In short current situation: 1. doUpdate2ndAJAX() execute 2. doUpdate2ndAJAX() not yet finish, start execute $(".search").click() 3. doUpdate2ndAJAX() Finish execute and response back

May I know how can I make it as 1. doUpdate2ndAJAX() execute 2. doUpdate2ndAJAX() Finish execute and response back 3. call $(".search").click();

[ Execute in sequence order ]

Thanks. -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 :

$.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.

You can read more about it in the jquery official documentation: JQuery Deferred Object

You should make the AJAX calls asynchronous, and call $(".search").click(); in the success callback for the second request.

Depending on your structure, you may want to add a parameter to doUpdate2ndAJAX which tells it whether to call $(".search").click(); .
Alternatively, you can add a callback parameter.

I suggest to use the "complete" callback to invoke the $(".search").click().

You can see the differences between success and complete callbacks here: http://api.jquery.com/jQuery.ajax/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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