Count the difference between async: false and async: true in Ajax requests

Time:2020-1-21

Examples are as follows:


function test(){
  var temp="00";
  $.ajax({
    async: false,
    type : "GET",
    url : 'userL_checkPhone.do',
    complete: function(msg){
      alert('complete');
    },
    success : function(data) {
      alert('success');
      temp=data;
      temp="aa";
    }
  });
  alert(temp);
  }

Checkphone() method in userlaction


  public void checkPhone() throws IOException {
    this.getServletResponse().setContentType("text/html; charset=UTF-8");
    this.getServletResponse().setHeader("Cache-Control", "no-cache");
    PrintWriter out = this.getServletResponse().getWriter();
    out.print("true");

  }

Async: false, (the default is true);

When async: false is synchronization, the Ajax request in the test () method locks the entire browser,

Other operations can only be performed after the execution of userl uucheckphone.do.

So the execution result is alert (‘success’); alert (‘complete ‘); alert (‘aa’);

When async: true, the Ajax request is asynchronous. But there is a problem: the Ajax request in test() and its subsequent operations are executed asynchronously, so when userl_checkphone.do has not finished executing, it may have already executed the subsequent operations of the Ajax request,

So the result is alert (‘success’); alert (‘complete ‘); alert (’00’);

In this way, it will be found that alert (“success”) and alert (Temp) are almost executed synchronously, so temp is the initialized value of temp = “00”, not temp = “AA”;

In the above article, the difference between async: false and async: true in Ajax requests is all that Xiaobian has shared with you. I hope you can give us a reference and support developepaer.