我写了不同的代码(至少两次),其中Ajax应该通过数据库调用(GET)来更改innerHTML值。虽然第一个请求在100%的时间内成功(更改数据库中的值),但下一个提取新信息以更新HTML文件的命令在大约20-30%的时间内失败,从而收到来自错误消息的响应xerver(旧值)。
我尝试跟踪该错误,但找不到,因为它仅在通话后才出现。以下代码只是我问题的相关部分。
<p>I like <b><span id="numCom"><?php echo liked_comments(); ?></span></b> comments.</p>
// Each comment has a likeComment and CountComments function that triggers the Ajax:
let likeIcon = document.getElementsByClassName("like-icon");
for(let i = 0; i < likeIcon.length; i++){
likeIcon[i].addEventListener("click", likeComment);
likeIcon[i].addEventListener("click", countComments);
}
function likeComment(){
let child = this.children[0];
let mainID = this.parentElement.parentElement.id;
url = "ajax/like_comment.php";
let xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function(){
if(this.status == 200){
let result = this.responseText;
if(result == "t"){
child.classList.remove("red-text");
} else if (result == "f") {
child.classList.add("red-text");
}
}
}
xhr.send("com_id=" + mainID);
}
function countComments(){
let numCom = document.getElementById("numCom");
let xhr = new XMLHttpRequest();
let url = "ajax/count_liked_comments.php";
xhr.open("GET", url, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.onload = function(){
if(this.status == 200){
numCom.innerHTML = this.responseText;
}
}
xhr.onerror = function(){
console.log("Error");
};
xhr.send();
}
// In the php-files these functions are executed:
function like_comment($id){
global $db;
$check_query = "SELECT liked FROM comments WHERE comment_id = $id LIMIT 1";
$check_result = mysqli_query($db, $check_query);
while($stm = mysqli_fetch_array($check_result)){
$l = $stm['liked'];
}
if($l == 0){
// UPDATE TO 1
$query = "UPDATE comments SET liked = 1 WHERE comment_id = $id LIMIT 1";
$result = mysqli_query($db, $query);
return $result;
} else if($l == 1) {
// UPDATE TO 0
$query = "UPDATE comments SET liked = 0 WHERE comment_id = $id LIMIT 1";
$result = mysqli_query($db, $query);
return $result;
}
}
function is_liked($id){
global $db;
$check_query = "SELECT liked FROM comments WHERE comment_id = $id LIMIT 1";
$check_result = mysqli_query($db, $check_query);
while($stm = mysqli_fetch_array($check_result)){
$l = $stm['liked'];
}
return $l;
}
function liked_comments(){
global $db;
$query = "SELECT comment_id FROM comments WHERE liked = 1";
$result = mysqli_query($db, $query);
return mysqli_num_rows($result);
}
代码仅是演示,并不是真正理解该问题的必要。在另一个项目中。我通过Ajax更改表行的值,然后要更新结果。这仅发生在大约70%到80%的时间中。其他所有时间均返回旧值