Home > Web Front-end > JS Tutorial > body text

What is the difference between async:false and async:true in Ajax requests?

php中世界最好的语言
Release: 2018-04-02 15:20:36
Original
1763 people have browsed it

This time I will bring you the difference between async:false and async:true in Ajax requests. What are the precautions when using async:false and async:true in Ajax requests? The following is a practical case, let’s take a look.

The example is 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);
  }
Copy after login

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");
  }
Copy after login
async: false, (default is true);

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

Only userL_checkPhone Only after the execution of .do is completed,

other operations can be performed.

So the execution result is first 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 the subsequent operations are executed asynchronously, so when userL_checkPhone.do has not yet been executed, the operations following the ajax request may have been executed,

So the result is alert('success'); alert('complete'); alert("00");

In this way, you will find that alert("success") and alert(temp) are executed almost simultaneously. So temp is the initialized value temp = "00", not temp="aa";

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

Ajax+mysql to create a message board function

Ajax steps to implement data paging query Detailed explanation

The above is the detailed content of What is the difference between async:false and async:true in Ajax requests?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template