2013-05-30 40 views
0

我正在使用AJAX請求來檢查某些內容是否爲真或假。下面是完整的功能,包括AJAX請求:如何在AJAX響應後退出父功能

function selectAnswer(id, questionId) { 
    $.get("php/forms/select-answer-process.php?scope=get&id="+questionId, function(data) { if (data == "true") { alert("You can only select one answer per question"); } }); 

    var confirmChoice = confirm("Are you sure you want to select this as the correct answer? This cannot be undone."); 
    if (confirmChoice) { 
     $.get("php/forms/select-answer-process.php?scope=save&id="+id); 
     document.getElementById("answer-check-"+id).src = "img/icons/check-green.png"; 
    } else { 
     return false; 
    } 
} 

警報的偉大工程,但我想退出父功能,如果Ajax響應是真實的。我怎樣才能做到這一點?

+1

你'ajax'調用是異步的,因此你不能過去從AJAX返回值的異步調用的基礎東西。你應該使用回調。 –

+2

您必須移動Ajax回調中的所有邏輯。如果您需要從父函數返回任何內容,則必須使其接受回調或使用承諾。有關更多信息,請參閱此問題:http://stackoverflow.com/q/14220321/218196。 –

回答

2

隨着Ajax是異步的,結果,ajax調用之後的任何內容在ajax調用完成後仍然會執行。相反,ajax返回後通常會使用回調來使用返回的數據。您應該使用在回調從AJAX調用返回這樣的數據:

function selectAnswer(id, questionId) { 
$.get("php/forms/select-answer-process.php?scope=get&id="+questionId, function(data) { 
    if (data == "true") { 
    alert("You can only select one answer per question"); 
    }else{ 
    successResponse(id);//callback when ajax is complete 
    } 
}); 
} 

//function to be called if ajax completion is successful and correct 
function successResponse(id){ 
var confirmChoice = confirm("Are you sure you want to select this as the correct answer? This cannot be undone."); 
if (confirmChoice) { 
    $.get("php/forms/select-answer-process.php?scope=save&id="+id); 
    document.getElementById("answer-check-"+id).src = "img/icons/check-green.png"; 
} 
} 
+0

美麗!謝謝... – Arun

0

您可以從塊內拋出一個異常,並抓住它的父母,然後把它處理需要:

try { 
    get block... { 
    if (data == "true") { 
     alert("You can only select one answer per question"); 
     throw "nope!"; 
    } 
    } 
} 
catch(ex) { 
    return false; 
} 
+0

我這樣做了,但它仍然移動到確認塊... – Arun

+0

'return false'在jquery中是有效的'break',並且只會跳出匿名函數。 –

+0

回調函數中的'return'語句對父函數沒有任何影響。 –

0

試試這個:

function selectAnswer(id, questionId) { 
    $.get("php/forms/select-answer-process.php?scope=get&id="+questionId, function(data) { 
     if (data == "true") { 
      alert("You can only select one answer per question"); 
      return; 
     } 
     var confirmChoice = confirm("Are you sure you want to select this as the correct answer? This cannot be undone."); 
     if (confirmChoice) { 
      $.get("php/forms/select-answer-process.php?scope=save&id="+id); 
      document.getElementById("answer-check-"+id).src = "img/icons/check-green.png"; 
     } else { 
      return false; 
     } 
    }); 
}