我正在使用 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 响应为 true,我想退出父函数。我怎样才能做到这一点?
最佳答案
由于 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";
}
}
关于javascript - AJAX响应后如何退出父函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16845549/