The difference between synchronous and asynchronous of async attribute value in ajax

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

 

Synchronization means that when the JS code is loaded into the current AJAX, other codes in the page will stop loading, and the page will appear in a suspended state. Only after this AJAX is executed, other code pages will continue to run, and the suspended animation state will be lifted. Asynchronous is when the AJAX code is running, and other code can run as well.

 

1. The value of async is true (asynchronous)

When ajax sends a request, in the process of waiting for the server to return, the foreground will continue to execute the script behind the ajax block until the server returns the correct result before executing the success, that is to say, two threads are executed at this time. , a thread after the ajax block makes the request and the script after the ajax block (another thread)

$.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 sends a request, it will stay in function1() and wait for the return from the server, but at the same time (during this waiting process), the foreground will execute function2().

 

2. The async value is false (synchronous)

When the current AJAX is executed, the execution of the subsequent JS code will be stopped, and the subsequent JS code cannot be executed until the AJAX is executed.

$.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 synchronous at this time, that is to say, after the ajax block sends a request at this time, it will wait at the place of function1() and will not execute function2() until function1( ) is partially executed.

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326565724&siteId=291194637