案例:所以我从后端收到JSON数据,我想在表格中显示这些数据。我正在创建一个名为 tableOutputString 的字符串,在迭代JSON时,我将响应连接到 tableOutputString 。最后我使用innerHTML来显示表格。
注意:查看"从这里开始"之间的代码和"在这里结束"。
问题:在函数内部我嵌套了AJAX。在内部AJAX中,我试图连接 tableOutputString ,但它没有发生。我认为存在一些范围问题。我在AJAX范围内时可以看到 tableOutputString 更新,但是一旦我从外部AJAX中走出来,我的字符串就像我进入AJAX之前一样。请帮帮我。
function displaytable(response) {
// Variable to check the length of the JSON abject
var lengthOfJSON = Object.keys(response).length;
var tableOutputString = "";
var Exam_id = "";
// creating the body part of the table
tableOutputString = tableOutputString + '<tbody>';
for (var i = 0; i < lengthOfJSON; i++) {
tableOutputString = tableOutputString + '<td>' + (i + 1) + '</td>';
for (var key in response[i]) {
if (key == "exam_name") {
Exam_id = response[i]["exam_id"];
tableOutputString = tableOutputString + '<td>' + '<a href="#"' + "onclick=getExam(" + Exam_id + ")>" + response[i][key] + '</a>' + '</td>';
} else {
tableOutputString = tableOutputString + '<td>' + response[i][key] + '</td>';
}
}
/* Starts Here */
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
if (response["taken"] == "true") {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
if (response["graded"] == "true") {
tableOutputString = tableOutputString + '<td>' + "graded" + '</td>'; // trying to concatenate
}
else {
tableOutputString = tableOutputString + '<td>' + "Not graded" + '</td>'; // trying to concatenate
}
}
};
xhttp.open("POST", "getWasUserExamGraded.php?id=" + Exam_id, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
}
else {
tableOutputString = tableOutputString + '<td>' + "Not taken" + '</td>'; // trying to concatenate
}
}
};
/* Ends Here */
xhttp.open("POST", "getDidTakeExam.php?id=" + Exam_id, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
tableOutputString = tableOutputString + '</tbody>'; //tableOutputString is not updated inside AJAX
document.getElementById("responstable").innerHTML = tableOutputString;
}
}
答案 0 :(得分:0)
我认为问题是您更新表格的时间,您是否尝试更新onreadystatechange
var cellText;
if (response["graded"] == "true") {
cellText = '<td id="gradedCell">' + "graded" + '</td>';
} else {
cellText = '<td id="gradedCell">' + "Not graded" + '</td>';
}
document.getElementById("gradedCell").innerHTML = cellText ;