ajax 同步異步

轉自 
http://blog.csdn.net/gaoyusi4964238/article/details/4378987 



這裏首先引用$.Ajax()中 async 和success的官方的解釋: 
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. 



在這裏,async默認的設置值爲true,這種狀況爲異步方式,就是說當ajax發送請求後,在等待server端返回的這個過程當中,前臺會繼續執行ajax塊後面的腳本,直到server端返回正確的結果纔會去執行success,也就是說這時候執行的是兩個線程,ajax塊發出請求後一個線程和ajax塊後面的腳本(另外一個線程)例: 

[javascript] view plaincopy 
$.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()部分執行完畢。 

          注:success中的方法f1(),f2()通常(即f1(),f2()不包括ajax塊時)不會異步執行,就是說f2的執行是以f1()爲前提的。javascript

相關文章
相關標籤/搜索