我需要根据我所做的 AJAX 调用还原对象。但是,我发现 AJAX 调用在函数完成执行之前没有完成。
我尝试了各种方法,但每种方法似乎都回到了相同的异步问题——我不想进行同步调用。
在我继续确定是否应该恢复之前,我如何以某种方式等到 AJAX 调用完成并且答案就在那里?
$(document).ready(function() {
$.ajax
({
type: "GET",
url: "quizData.xml",
dataType: "xml",
success: function(xml)
{
var questionIdCount = 0;
$(xml).find('question').each(function()
{
questionIdCount++;
$("#question-container").append("<div class=\"question\" id=\"question-number-" + questionIdCount + "\">" + $(this).text() + "</div>");
$("#question-number-" + questionIdCount).data('id', questionIdCount);
$(".question").droppable(
{
}
);
});
var answerIdCount = 0;
$(xml).find('answer').each(function()
{
answerIdCount++;
$("#answer-container").append("<div class=\"answer-id\" id=\"answer-number-" + answerIdCount +
"\">" + answerIdCount + "</div><div class=\"answer\">" + $(this).text() + "</div>");
$("#answer-number-" + answerIdCount).data('id', answerIdCount);
$(".answer-id").draggable({
revert: function(socketObj)
{
if(!socketObj)
{
return true;
}
else
{
var questionId = $("#" + socketObj.attr('id')).data('id')
var answerId = $("#" + $(this).attr('id')).data('id');
return checkAnswer(questionId, answerId);
}
},
containment: "#containment-wrapper",
scroll: true
});
});
}
});
$(document).ready(function() {
$.ajax
({
type: "GET",
url: "quizData.xml",
dataType: "xml",
success: function(xml)
{
var questionIdCount = 0;
$(xml).find('question').each(function()
{
questionIdCount++;
$("#question-container").append("<div class=\"question\" id=\"question-number-" + questionIdCount + "\">" + $(this).text() + "</div>");
$("#question-number-" + questionIdCount).data('id', questionIdCount);
$(".question").droppable(
{
}
);
});
var answerIdCount = 0;
$(xml).find('answer').each(function()
{
answerIdCount++;
$("#answer-container").append("<div class=\"answer-id\" id=\"answer-number-" + answerIdCount +
"\">" + answerIdCount + "</div><div class=\"answer\">" + $(this).text() + "</div>");
$("#answer-number-" + answerIdCount).data('id', answerIdCount);
$(".answer-id").draggable({
revert: function(socketObj)
{
if(!socketObj)
{
return true;
}
else
{
var questionId = $("#" + socketObj.attr('id')).data('id')
var answerId = $("#" + $(this).attr('id')).data('id');
return checkAnswer(questionId, answerId);
}
},
containment: "#containment-wrapper",
scroll: true
});
});
}
});
function checkAnswer(questionId, answerId)
{
var ajaxAnswer;
$.ajax
({
type: "POST",
url: "getQuizAnswers.php",
dataType: "xml",
data: "questionId=" + questionId + "&answerId=" + answerId,
success: function(xml)
{
console.log($(xml));
$(xml).find("answer").each(function()
{
//alert($(this).text());
if($(this).text() == "true")
ajaxAnswer = true;
else
ajaxAnswer = false;
});
}
})
return ajaxAnswer;
}
});
});