What does “async: false” do in jQuery.ajax()?

后端 未结 7 1626
北海茫月
北海茫月 2020-11-22 01:47

Specifically, how does it differ from the default ( async: true ) ?

In what circumstances would I want to explicit set async to fals

7条回答
  •  广开言路
    2020-11-22 02:27

    Setting async to false means the instructions following the ajax request will have to wait for the request to complete. Below is one case where one have to set async to false, for the code to work properly.

    var phpData = (function get_php_data() {
      var php_data;
      $.ajax({
        url: "http://somesite/v1/api/get_php_data",
        async: false, 
        //very important: else php_data will be returned even before we get Json from the url
        dataType: 'json',
        success: function (json) {
          php_data = json;
        }
      });
      return php_data;
    })();
    

    Above example clearly explains the usage of async:false

    By setting it to false, we have made sure that once the data is retreived from the url ,only after that return php_data; is called

提交回复
热议问题