Ajax sync vs async

When I have been writing JQUERY code before, I need to consider the order of code running when I encounter AJAX loading data. A recent project uses AJAX synchronization. This synchronization means that when the JS code is loaded into the current AJAX, all the code in the page will be stopped from loading, and the page will go out of the suspended state. When the AJAX is executed, it will continue to run other codes and the suspended state of the page will be released. 

Asynchronous means that other code can run while the AJAX code is running. jQuery's async: false, this property defaults to true: asynchronous, false: synchronous.

$.ajax({ 

        type: "post", 

        url: "path", 

        cache:false, 

        async:false, 

        dataType: ($.browser.msie) ? "text" : "xml", 

         success: function(xmlobj){ 

        } 

});

With this property, the problem of code running book sequence can be relatively reduced, but if it is used too much, the number of page suspended animations will be too many. This will lead to a poor user experience~!

The official explanation of async and success in $.Ajax():

async 
Boolean 
Default: true

By default, all requests are sent asynchronous (e.g. this is set to true by default). If you need synchronous requests, set this option to false. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

success 
Function

A function to be called if the request succeeds. The function gets passed two arguments: The data returned from the server, formatted according to the 'dataType' parameter, and a string describing the status. This is an Ajax Event.

 

Here, the default setting value of async is true, which is asynchronous, that is, when ajax sends a request, while 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 will execute the success, that is to say, two threads are executed at this time, one thread after the ajax block makes the request and the script (another thread) after the ajax block. Example:

$.ajax({  

          type:"POST", 

         url:"Venue.aspx?act=init", 

           dataType:"html", 

          success:function(result){   //function1()

             f1(); 

             f2(); 

        } 

         failure:function (result) {  

            alert('Failed');  

         }, 

  } 

  function2(); 

      在上例中,当ajax块发出请求后,他将停留function1(),等待server端的返回,但同时(在这个等待过程中),前台会去执行function2(),也就是说,在这个时候出现两个线程,我们这里暂且说为function1() 和function2()。

      当把asyn设为false时,这时ajax的请求时同步的,也就是说,这个时候ajax块发出请求后,他会等待在function1()这个地方,不会去执行function2(),知道function1()部分执行完毕。

文章出处 : https://www.cnblogs.com/xmphoenix/archive/2011/11/21/2257651.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325886625&siteId=291194637