在AJAX成功后如何刷新div元素?

时间:2016-10-29 18:31:04

标签: javascript html ajax

发布这个因为我发现了很多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函数没有执行。

1 个答案:

答案 0 :(得分:4)

您应该允许将评论发送到服务器并在致电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();
}
相关问题