DIV CSS 佈局教程網

Ajax 請求中 async 設置 false 與 true 的作用分析
編輯:AJAX基礎知識     

$.ajax 裡有個參數叫 async,控制着請求是同步還是異步。這個看似不起眼的設置,實際上對執行流程影響巨大。本文用一個小例子,直觀地剖析 async:false 與 async:true 的區別。

test.html 代碼:

 <a href="javascript:void(0)" onmouseover="testAsync()"> 

asy.js 代碼:

 function testAsync(){ var temp; $.ajax({ async: false, type : "GET", url : 'tet.php', complete: function(msg){ alert('complete'); }, success : function(data) { alert('success'); temp=data; } }); alert(temp+' end'); }

tet.php 代碼:

 <?php echo "here is html code"; sleep(5); ?> 

先看 async: false(默認是 true)。此時為同步請求,testAsync() 方法中的 Ajax 會把整個浏覽器鎖死,只有等 tet.php 執行結束後,才能執行其他操作。也就是說,代碼會嚴格按照「先請求、後 alert」的順序執行,temp 能正確拿到值。

再看 async: true。此時 Ajax 請求是異步的,但問題也隨之而來:testAsync() 裡的 Ajax 請求與其後面的操作是異步執行的。當 tet.php 還沒執行完(這裡 sleep 了 5 秒),後面的 alert(temp+' end') 就可能已經先跑了。而 temp 是在 success 回調裡才賦值的,結果輸出時 temp 就是空的。

這個例子說明:大多數場景下我們用異步(async:true)以免阻塞界面;但當後續邏輯確實依賴請求結果、又無法放進回調裡時,才會考慮同步。理解這個差異,能幫你避免不少「數據莫名為空」的坑。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved