Make sure first ajax function finishes before second one

前端 未结 9 1226
無奈伤痛
無奈伤痛 2021-01-18 01:41

I have a JavaScript function that makes two consecutive Ajax requests using jQuery. I want to make sure that the first request has loaded before the second function is call

相关标签:
9条回答
  • 2021-01-18 02:00

    An example implementation:

    function callback() {$('div#second_ajax_output').load('http://www.google.com');}
    $('div#first_ajax_output').load('http://www.yahoo.com',callback);
    
    0 讨论(0)
  • 2021-01-18 02:03
    $.post("script1.php", {data:"val"}, function(response) {
      $.post("script2.php", {data:response}, function(results) {
        // this second call will be initialized when the first finishes
      });
    });
    
    0 讨论(0)
  • 2021-01-18 02:04

    Using jQuery the simplest way is like this:

     $.ajax({
       type: "POST",
       url: "some.php",       
        success: function(msg){
           $.ajax({
             type: "POST",
             url: "some2.php",
    
             success: function(msg){
                 alert( "End of second call" );
             }
          });
        }
     });
    
    0 讨论(0)
  • 2021-01-18 02:12

    Either specify async: false in the $.ajax options, or make the second ajax call in the complete callback of the first call.

    0 讨论(0)
  • 2021-01-18 02:12

    In your callback for the first function, make your second call.

    0 讨论(0)
  • 2021-01-18 02:17

    The simple way is to fire the second request when the first returns (in the complete callback).

    If you need a more sophisticated approach take a look at the AjaxQueue plug-in. You can queue requests this way.

    0 讨论(0)
提交回复
热议问题