0

我正在使用 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 响应为真,我想退出父函数。我怎样才能做到这一点?

4

3 回答 3

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";
 }
}
于 2013-05-30T20:52:21.667 回答
0

您可以从块内部抛出异常并在父级中捕获它,然后根据需要处理它:

try {
  get block... {
    if (data == "true") { 
      alert("You can only select one answer per question"); 
      throw "nope!";
    }
  }
}
catch(ex) {
  return false;
}
于 2013-05-30T20:45:12.090 回答
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;
        }
    });
}
于 2013-05-30T20:50:35.887 回答