发布此消息是因为我发现了很多jquery答案,但是没有原始的javascript答案。

因此,我具有将评论发布到评论部分的功能,并且我希望在发布评论后刷新评论部分,但是由于某些原因,我的代码无法正常工作。

加载注释部分的代码:

function loadCommentSection() {
 console.log("loading section")
  imgid = imgid.replace("img/pic (", "");
  imgid = imgid.replace(").jpg", "");
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
    document.getElementById("commentsection").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "commentsection.php?imgid=" + imgid, true);
  xhttp.send();
}


以及提交评论的代码:

function submitComment() {
  var title = document.getElementById("title").value;
  var name = document.getElementById("name").value;
  var comment = document.getElementById("comment").value;

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     document.getElementById("msg").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "comment.php?imgid=" + imgid + "&title=" + title + "&comment=" + comment + "&name=" + name, true);

  xhttp.send();
  loadCommentSection();


}


问题在于submitComment函数中的loadCommentSection函数未执行。

最佳答案

在调用loadCommentSection之前,应允许将注释发送到服务器并进行注册。因此,最好在响应可用时调用它:

function submitComment() {
  var title = document.getElementById("title").value;
  var name = document.getElementById("name").value;
  var comment = document.getElementById("comment").value;

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("msg").innerHTML = this.responseText;
      loadCommentSection(); // <<---- moved here.
    }
  };
  xhttp.open("GET", "comment.php?imgid=" + imgid + "&title=" + title + "&comment=" + comment + "&name=" + name, true);
  xhttp.send();
}

09-25 18:33
查看更多