how to wait for an ajax call to return

前端 未结 6 841
天涯浪人
天涯浪人 2021-01-12 20:00

I\'m trying to use JQuery although i\'m struggling to successfully wait for a ajax call to succeed before executing further code. Is there a way to wait for an ajax to call

6条回答
  •  不知归路
    2021-01-12 20:51

    Yes, you can do request synchronously:

    var bodyContent = $.ajax({
          url: "script.php",
          global: false,
          type: "POST",
          data: {id : this.getAttribute('id')},
          dataType: "html",
          async:false,
          success: function(msg){
             alert(msg);
          }
       }
    ).responseText;
    

    Source: http://api.jquery.com/jQuery.ajax/

    However, synchronous requests are a step backwards, as the JS engine (and, in some browsers, the user interface) will block until the request completes. Douglas Crockford once wrote about synchronous requests:

    Synchronous programming is disrespectful and should not be employed in applications which are used by people.

提交回复
热议问题