AJAX同步與非同步

來源:互聯網
上載者:User

標籤:des   http   io   os   ar   for   strong   sp   資料   

今天來大概說說AJAX中的同步與非同步。其實,就我的理解,同步與非同步區別就是程式執行過程中是否有等待。

同步:意思就是js代碼載入到當前的 AJAX時候,會等待AJAX代碼執行完畢後再開始載入其他代碼;

非同步:js代碼是指當載入到 AJAX時候,在AJAX代碼執行的同時 ,也會執行其他代碼。

jquery 的async 屬性:預設 情況下 ,為true  :非同步,                                         標註為false:表示同步

 

 

官方解釋:

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.

翻譯如下:非同步處理方式:傳回型別為boolean型,

預設情況下所以請求為非同步方式處理,傳回值是true;如果需要同步的要求,可以傳回值設定為false,但是請注意:在同步請求的時候,可能會暫時鎖定瀏覽器,其他任何行為均被禁止,而同步請求行為是活動的。

 

 

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.

翻譯如下:當函數請請求返回成功時,將會得到2個參數,1.從伺服器端返回的資料。2.根據資料類型參數的格式化和描述狀態的字串,這個被成為 一個ajax事件。

 

 

非同步:當ajax發送請求後,在等待 server端返回的過程中,前台會繼續執行ajax後面的代碼,直到server端返回正確的結果,才會執行success,即無等待過程,執行的時候分為2個線程。

看下如下的代碼:

$.ajax({  

          type:"POST", 

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

           dataType:"html", 

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

                 f1(); 

                 f2(); 

                 } 

          failure:function (result) {  

            alert(‘Failed‘);  

             }

      } 

   function2(); 

前面我們已經說到,預設情況下async預設為true, 非同步處理方式,就是說當ajax發送請求後,將停留在function1(),在等待伺服器返回結果,但在等待過程中 ,前台會繼續執行function2(),此時就出現了 2個線程。

 

同步 處理方式:當把async設為false,在ajax發出請求後,會等待function1(),並不會執行function2(),直到function1()的部分執行完畢為止 。

 

AJAX同步與非同步

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.