我目前正在做一个"反应"用于类似社交网络的Web应用程序的系统。
当用户单击按钮时,会向处理GET数据并返回的PHP文件发送AJAX请求。
问题是,我只能同步发出请求,否则" onreadystatechange"函数变量最终被声明,控制台抛出一个错误。这是代码:
var xhttp = new XMLHttpRequest();
var posts = document.getElementsByClassName("post");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200 && this.responseText != "0") {
eval("var query_" + autor + " = [];");
eval("var query_" + autor + " = JSON.parse(this.responseText)");
eval("var j = query_" + autor + ";");
var rUp = posts[i].querySelector(".divReacao").querySelector(".txtReacao");
if (typeof j[index]['reacoesUp'] != 'undefined') {
if (Object.keys(j[index]['reacoesUp']).length == 0 || j[index]['reacoesUp'].length == 0) {
rUp.innerHTML = "Monstro (0)";
} else {
var nUp = String(j[index]['reacoesUp'].length);
rUp.innerHTML = "Monstro" + " (" + nUp + ")";
}
if (j[index]['reacoesUp'].includes(getCookies()["usuario"])) {
posts[i].querySelector(".divReacao").style.backgroundColor = "#a7c7cf";
} else {
posts[i].querySelector(".divReacao").style.backgroundColor = "white";
}
} else {
rUp.innerHTML = "Monstro (0)";
}
}
};
xhttp.open("GET", "ajax.php?req=query_autores&autor=" + autor + "&t=" + String(Math.random()), false);
xhttp.send();
我得到的控制台消息是" Uncaught TypeError:无法读取属性' querySelector'未定义的。
如何在onreadystatechange中延迟声明变量以便异步执行请求?