jquery的ajax同步和非同步理解及樣本_AJAX相關

來源:互聯網
上載者:User
之前一直在寫JQUERY代碼的時候遇到AJAX載入資料都需要考慮代碼運行順序問題。最近的項目用了到AJAX同步。這個同步的意思是當JS代碼載入到當前AJAX的時候會把頁面裡所有的代碼停止載入,頁面出去假死狀態,當這個AJAX執行完畢後才會繼續運行其他字碼頁面假死狀態解除。
而非同步則這個AJAX代碼運行中的時候其他代碼一樣可以運行。
jquery的async:false,這個屬性
預設是true:非同步,false:同步。
複製代碼 代碼如下:

$.ajax({

type: "post",

url: "path",

cache:false,

async:false,

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

success: function(xmlobj){

}

});

有了這個屬性可以相對的減少代碼運行書序問題,但是如果用的太多,頁面假死次數太多。這樣反而導致使用者體驗不佳~!

$.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塊後面的指令碼(另一個線程)例:
複製代碼 代碼如下:

$.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()部分執行完畢。
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.