Ajax 同步和異步的區別
同步是當 JS 代碼加載到當前 Ajax 的時候會把頁面里所有的代碼停止加載,頁面出現假死狀態;當這個 Ajax 執行完畢后才會繼續運行其他代碼此時頁面假死狀態才會解除。反之異步則 Ajax 代碼在運行時,其余的 JS 腳本依舊能夠運行。
在 Jquery 中可以通過 async 的 true 和 false 設置同步或異步,在默認的情況下是為 true 即為異步。
接下來請看下 Sample Code:
$.ajax({ type: "post", url: "path", cache:false, async:false, dataType: "xml" success: function(obj){ } });
async 這個屬性可以相對的減少代碼運行順序問題,但是用的太多的也可能導致頁面假死的次數太多,容易降低用戶體驗。
參考官方給出的解釋:
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 ,這種就為異步方式(如果忘記了概念,可參考文章開端簡介)
這種執行方式其實執行是有兩個線程, 服務端請求一個,后面的 JS 腳本一個。
Sample Code:
$.ajax({ type:"POST", url:"xx.aspx=init", dataType:"xml", success:function(data){ //function1() f1(); f2(); } failure:function (data) { alert('Failed'); }, } function2();
在上例中,當ajax塊發出請求后,他將停留function1(),等待server端的返回,但同時(在這個等待過程中),前台會去執行function2(),也就是說,在這個時候出現兩個線程,我們這里暫且說為function1() 和function2()。
當把asyn設為false時,這時ajax的請求時同步的,也就是說,這個時候ajax塊發出請求后,他會等待在function1()這個地方,不會去執行function2(),知道function1()部分執行完畢。
