先看一段看似正常、卻總是拿不到預期回值的程式碼:
function getReturnAjax(){
$.ajax({
type:"POST",
url:"userexist.aspx",
data:"username="+vusername.value,
success:function(msg){
if(msg=="ok"){
return true;
}
else{
return false;
}
}
});
}
呼叫 getReturnAjax() 時,你會發現無論如何都只得到 false,return true 與 return false 根本沒有效果。用 Firebug 除錯也會發現,程式根本不會執行到 return 那一段。
嘗試在函數中先宣告一個變數、在 ajax 內賦值、最後於函數末尾回傳,看起來似乎也沒用:
function getAjaxReturn(){
var bol=false;
$.ajax({
type:"POST",
url:"userexist.aspx",
data:"username="+vusername.value,
success:function(msg){
bol=true;
}
});
return bol;
}
問題依舊存在。這背後有兩種成熟的解法。
設定 async:false 後,ajax 會等到有了回傳值才繼續往下執行後面的程式。也就是說,程式會先等 bol 被賦值,再執行 return,如此一來自然就能拿到正確結果。過去很多「ajax 裡賦值卻不生效」的困惑,根源往往就在這裡。
function getAjaxReturn(){
var bol=false;
$.ajax({
type:"POST",
async:false,
url:"userexist.aspx",
data:"username="+vusername.value,
success:function(msg){
bol=true;
}
});
return bol;
}
另一種更靈活的思路,是把成功與失敗的處理邏輯交由傳入的函數負責:
function getAjaxReturn(success_function,fail_function){
$.ajax({
type:"POST",
url:"userexist.aspx",
data:"username="+vusername.value,
success:function(msg){
if(msg=="ok"){ success_function(msg); }
else{ fail_function(msg); }
}
});
}
這種做法更貼近 Ajax 的非同步本質,也更容易維護。理解同步與異步的差別,是寫好 Ajax 互動的關鍵一步。