Javascript node.js无法正常工作的jQuery AJAX请求

Javascript node.js无法正常工作的jQuery AJAX请求,javascript,jquery,node.js,ajax,ejs,Javascript,Jquery,Node.js,Ajax,Ejs,因此,我试图做出实时评论,但评论不断重复,并用文本填充页面。我如何阻止这种情况发生。 我的客户端代码 显示路线 <%- include("../partials/header") %> <h1><%- video.title %></h1> <div><%- video.file %></div> <p><%- video.description %></p&g

因此,我试图做出实时评论,但评论不断重复,并用文本填充页面。我如何阻止这种情况发生。
我的客户端代码
显示路线

<%- include("../partials/header") %>
<h1><%- video.title %></h1>
<div><%- video.file  %></div>
<p><%- video.description %></p>
<% if(auth){ %>
<% if(auth.username === "Puffier_Fisher"){ %> 
<button class="btn btn-success"><a href="/videos/<%= video._id %>/edit" class="text-white">EDIT</a></button>
<form action="/videos/<%= video._id %>?_method=delete" method="post">
<button type="submit" class="btn btn-danger">DELETE!</button>
</form>
<% } else {} %>
<% } %>
<button class="btn btn-primary"><a href="/videos/<%= video._id %>/comments/new" class="text-white">New Comment</a></button><br>
<div id="comments"></div>
<script>
    function findComments() {
    $.ajax({
        dataType:"json",
        url: "/videos/<%= video._id %>/comments",
        type: "GET",
        success: function(res){
            res.forEach(comment => {
                $("#comments").append(`<strong>${comment.author}</strong>`, "<br>");
                $("#comments").append(`<p>${comment.text}</p>`);
            });
        }
    });
}
findComments();
setInterval(findComments, 5000);
</script>
<%- include("../partials/footer") %>
router.get("/videos/:id/comments", function(req, res){
    Video.findById(req.params.id).populate("comments").exec(function (err, foundVideo) {
        if (err) {
            console.log(err)
        } else {
            let doc = JSON.stringify(foundVideo.comments);
            res.send(doc)
        }
    });
});

setInterval(findComments,5000)
每5秒调用一次
findComments
——每次调用都会得到额外(同样)的输出。您不想只调用它一次,如
findComments()
。(您的
findComments
接受一个参数
i
,但它似乎没有实际用于函数中。)哦,我明白了。您有可能以这种方式使用自己的服务器,但没关系。您可以在函数开始时清除
#comments
的内容,或者(更好)在Ajax成功回调开始时清除内容。一般来说,如果您想获得“实时”,不断从服务器更新信息,您需要考虑使用WebSocket。这是一种不好的方法。在循环中,检查#注释是否已经包含该注释。如果$(“:contains(comment)”)如上所述,您有可能给服务器添加剂量。