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);
如上:false為同步,這個 testAsync()方法中的Ajax請求將整個瀏覽器鎖死,
只有tet.php執行結束后,才可以執行其它操作。
當async: true 時,ajax請求是異步的。但是其中有個問題:testAsync()中的ajax請求和其后面的操作是異步執行的,那么當tet.php還未執行完,就可能已經執行了 ajax請求后面的操作,
如: alert(temp+' end');
然而,temp這個數據是在ajax請求success后才賦值的,結果,輸出時會為空。