search
HomeWeb Front-endJS TutorialThe difference between synchronization and asynchronous and synchronization and asynchronousness of async attribute value in ajax

Async is used to control synchronization and asynchronousness in the ajax method in Jquery. When the async value is true, it is an asynchronous request, and when the async value is false, it is a synchronous request. The async attribute in ajax is used to control the way data is requested. The default is true, which means that data is requested asynchronously by default.

The ajax method in jquery has an attribute async for controlling synchronization and asynchronousness. The default is true, that is, the ajax request is an asynchronous request by default. Sometimes AJAX synchronization is used in projects. What this synchronization means is that when the JS code is loaded into the current AJAX, all the code in the page will stop loading, and the page will appear in a state of suspended animation. When the AJAX is completed, it will continue to run other codes and the page's suspended state will be lifted. Asynchronously, other codes can run while this AJAX code is running.

The async attribute in ajax is used to control the way of requesting data. The default is true, which means that data is requested asynchronously by default.

1. The async value is true (asynchronous)

When ajax sends a request, while waiting for the server to return, the foreground will continue to execute the ajax block. The script will not execute success until the server returns the correct result. That is to say, two threads are executed at this time, one thread after the ajax block sends the request and the script after the ajax block (another thread)

For example

$.ajax({  
     type:"POST", 
     url:"Venue.aspx?act=init", 
      dataType:"html", 
     success:function(result){  //function1()
       f1(); 
       f2();  
    } 
     failure:function (result) {  
      alert('Failed');  
     }, 
 } 
 function2();

In the above example, when the ajax block makes a request, it will stay in function1() and wait for the return from the server side, but At the same time (during this waiting process), the front desk will execute function2().

2. The async value is false (synchronous)

When the current AJAX is executed, the subsequent JS code will stop executing until the AJAX is completed. , to continue executing the following JS code.

For example

$.ajax({  
     type:"POST", 
     url:"Venue.aspx?act=init", 
     dataType:"html", 
     async: false,
    success:function(result){  //function1()
       f1(); 
       f2(); 
     } 
    failure:function (result) {  
      alert('Failed');  
     }, 
 } 
 function2();

When asyn is set to false, the ajax request is synchronized, and That is to say, after the ajax block sends a request at this time, it will wait at function1() and will not execute function2() until the function1() part is completed.

The difference between Ajax synchronization and asynchronous

var returnValue = null; 
xmlhttp = createXmlHttp(); 
xmlhttp.onreadystatechange = function() { 
  if(xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
    if (xmlhttp.responseText == "true") { 
      returnValue = "true"; 
    } 
    else { 
      returnValue = "false"; 
    } 
  } 
}; 
xmlhttp.open("Post",url,true); //异步传输 
xmlhttp.setRequestHeader("If-Modified-Since","0"); //不缓存Ajax
xmlhttp.send(sendStr); 
return returnValue;

xmlHttpReq can only be used asynchronously .onreadystatechange status value! The following are the different calling methods of asynchronous and synchronous:

Java

xmlHttpReq.open("GET",url,true);//异步方式
  xmlHttpReq.onreadystatechange = showResult; //showResult是回调函数名
  xmlHttpReq.send(null);
function showResult(){  
  if(xmlHttpReq.readyState == 4){   
   if(xmlHttpReq.status == 200){
   ******
   }
  }
}

Java

xmlHttpReq.open("GET",url,false);//同步方式  
      xmlHttpReq.send(null);  
      showResult(); //showResult虽然是回调函数名但是具体用法不一样~  
function showResult(){   
       //if(xmlHttpReq.readyState == 4){  这里就不用了,直接dosomething吧~  
        //if(xmlHttpReq.status == 200){  
          ******//dosomething  
        //}  
      //}  
}
xmlhttp.open("Post",url,true);

If it is synchronous (false), the return value is true or false, because after executing send, onreadystatechange starts to be executed, and the program will wait until onreadystatechange is completed. The next statement will not be executed until responseText is obtained, so returnValue must have a value.

If it is asynchronous (true), the return value must be null, because the program does not wait for the response of xmlhttp after executing send, and continues to execute the next statement, so the returnValue has returned null before it has changed. .

If you want to get the xmlhttp return value, you must use synchronization. The return value cannot be obtained asynchronously.

Be careful when using the xmlhttp pool synchronously and asynchronously: when obtaining xmlhttp, you can only create a new xmlhttp, and you cannot take out the used xmlhttp from the pool, because the readyState of the used xmlhttp is 4, so Both synchronous and asynchronous will send but do not execute onreadystatechange.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Understanding the datatype attribute option value in jquery ajax

Realize N seconds interval based on Jquery ajax technology Passing values ​​to a page

Solve the forward and backward problems of ajax based on Jquery.history

The above is the detailed content of The difference between synchronization and asynchronous and synchronization and asynchronousness of async attribute value in ajax. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor