Ajax函数无法正常删除和更新注释

时间:2017-05-18 12:01:41

标签: node.js ajax

我在博客项目的评论部分使用Ajax。它工作正常然而显然我已经改变了一些东西,因为现在当我去编辑评论时它不起作用,当我尝试删除时,它确实会破坏评论但它也会消除一大堆其他评论,直到我当一切看起来都很好时刷新页面。现在唯一正在运行的Ajax函数是创建新注释。

这是我的评论部分的显示页面代码:

<!--================== COMMENTS DISPLAY SECTION ====================================================================-->
<div id="comments">
    <% blog.comments.forEach(function(comment){ %>
    <div class="comment-container">
        <div class="jumbotron comment">
            <div class="row">
                <div class="col-md-1">
                    <img class="comment-ico" src = "<%=comment.author.image%>">
                </div>

                <div class="col-md-7">
                    <h4><%=comment.author.username%></h4>
                </div>
            </div>
        </div>
            <div><p><%=comment.text%></p></div>

<!--=================EDIT COMMENT FORM =========================================================================-->
       <form id="edit-comment-form" action = "/blogs/<%= blog._id %>/comments/<%=comment._id%>?_method=PUT" method = "POST" id="newComment">
            <textarea class = "form-control" rows="4" name = "comment[text]"><%=comment.text%></textarea>
            <button class = "btn btn-lg btn-primary btn-block">Submit</button>
        </form>

<!--==================================================================================================================-->

        <!-- if current user is the same as author -->

        <% if(currentUser && currentUser.username == comment.author.username) { %>
            <div class="row">
                <div class="col-md-1 choice">
                    <a class="edit">Edit</a>
                </div>
                <div class="col-md-1">
                    <form id = "delete-form" action = "/blogs/<%= blog._id %>/comments/<%=comment._id%>?_method=DELETE" method = "POST">
                    <input type = "submit" class = "button-delete" value = "Delete"></form>
                </div>
                <% } %>
                <% if(currentUser && currentUser.username == comment.author.username) { %>
                <div class="col-md-1 choice-report">
                    <a class="report">Report</a>
                </div>
                <% } else { %>
                <div class="col-md-1 choice-no-user">
                    <a href="/blogs/<%=blog._id%>/comments/<%=comment._id%>/report" class="report">Report</a>
                </div>
                <% } %>

            </div>
        <br>
        <hr class = "style-three">
        <% }) %>
    </div>

</div>
</div>

<!--==================================================================================================================-->




<% if(currentUser){ %>
<div class = "container-form">
   <form action = "/blogs/<%= blog._id %>/comments" method = "POST" id="newComment">
    <div class="row">
        <div class="col-md-2">
            <img class="newComment-ico" src = " <%=currentUser.image%>">
        </div>
        <div class="col-md-10">
            <label for="comment">Add comment</label>
        </div>
    </div>
        <textarea class = "form-control" rows="4" placeholder = "Type comment here..." name = "comment[text]"></textarea>
        <button class = "btn btn-lg btn-primary btn-block">Submit</button>
    </form>
</div>

<% } %>

我的Ajax代码:

// update comment
$('#comments').on('submit', '#edit-comment-form', function(e){
e.preventDefault();
// get info from form
var formData = $(this).serialize();
var formAction = $(this).attr('action');
var $originalItem = $(this).parent('.comment-container');
$.ajax({
    url: formAction,
    data: formData,
    type: 'PUT',
    originalItem: $originalItem,
    success: function(data) {
        var blog_id = location.pathname.replace("/blogs/", "");
        this.originalItem.html(
            `
          <div class="comment-container">
        <div class="jumbotron comment">
            <div class="row">
                <div class="col-md-1">
                    <img class="comment-ico" src = "${data.author.image}">
                </div>

                <div class="col-md-7">
                    <h4>${data.author.username}</h4>
                </div>
            </div>
        </div>
            <div><p>${data.text}</p></div>

       <form id="edit-comment-form" action = "/blogs/${blog._id}/comments/${data._id}?_method=PUT" method = "POST" id="newComment">
            <textarea class = "form-control" rows="4" name = "comment[text]">${data.text}</textarea>
            <button class = "btn btn-lg btn-primary btn-block">Submit</button>
        </form>


            <div class="row">
                <div class="col-md-1 choice">
                    <a class="edit">Edit</a>
                </div>
                <div class="col-md-1">
                    <form id = "delete-form" action = "/blogs/${blog._id}/comments/${data._id}?_method=DELETE" method = "POST">
                    <input type = "submit" class = "button-delete" value = "Delete"></form>
                </div>

                <div class="col-md-1 choice-report">
                    <a class="report">Report</a>
                </div>
            </div>
        <br>
        <hr class = "style-three">
            `
            );
    }
});
});

这是更新评论路线:

// comment update route
router.put("/:comment_id", function(req, res){
Comment.findByIdAndUpdate(req.params.comment_id, req.body.comment,  {new: true}, function(err, updatedComment){
    if(err) {
        res.redirect("back");
    } else {
        if(req.xhr);
            res.json(updatedComment);
        // } else {
        // res.redirect("/blogs/" + req.params.id);
        // }
    }
})
})

我的破坏Ajax代码:

// delete comments asynchonously
$('#comments').on('submit', '#delete-form', function(e){
e.preventDefault();
var confirmResponse = confirm('Are you sure you want to delete this comment?');
if(confirmResponse){
    var actionURL = $(this).attr('action');
    $itemToDelete = $(this).closest('.comment-container');
    $.ajax({
        url: actionURL,
        type: 'DELETE',
        itemToDelete: $itemToDelete,
        success: function(data){
            this.itemToDelete.remove();
        }
    })
} else {
    $(this).find('input').blur();
}
})

摧毁路线:

// comments destroy route
router.delete("/:comment_id", function(req, res){
Comment.findByIdAndRemove(req.params.comment_id, function(err, comment){
    if(err) {
        res.redirect("back");
    } else {
        res.json(comment);
    }
})
})

更新:

我注意到我的Ajax代码上有一些错误,我引用了$ {blog._id}而不是$ {blog_id}。我更新如下:

// update comment
$('#comments').on('submit', '#edit-comment-form', function(e){
e.preventDefault();
// get info from form
var formData = $(this).serialize();
var formAction = $(this).attr('action');
var $originalItem = $(this).parent('.comment-container');
$.ajax({
    url: formAction,
    data: formData,
    type: 'PUT',
    originalItem: $originalItem,
    success: function(data) {
        var blog_id = location.pathname.replace("/blogs/", "");
        this.originalItem.html(
            `
            <div class="jumbotron comment">
            <div class="row">
                <div class="col-md-1">
                    <img class="comment-ico" src = "${data.author.image}">
                </div>

                <div class="col-md-7">
                    <h4>${data.author.username}</h4>
                </div>
            </div>
        </div>
            <div><p>${data.text}</p></div>

       <form id="edit-comment-form" action = "/blogs/${blog_id}/comments/${data._id} method = "POST" id="newComment">
            <textarea class = "form-control" rows="4" name = "comment[text]">${data.text}</textarea>
            <button class = "btn btn-lg btn-primary btn-block">Submit</button>
        </form>


            <div class="row">
                <div class="col-md-1 choice">
                    <a class="edit">Edit</a>
                </div>
                <div class="col-md-1">
                    <form id = "delete-form" action = "/blogs/${blog_id}/comments/${data._id}?_method=DELETE" method = "POST">
                    <input type = "submit" class = "button-delete" value = "Delete"></form>
                </div>

                <div class="col-md-1 choice-report">
                    <a class="report">Report</a>
                </div>
            </div>
        <br>
        <hr class = "style-three">
            `
            );
    }
});
});

现在注释将异步更新,但是在页面刷新之前,它再次启动了大量其他注释。实际上,它正在暂时删除正在编辑的注释之下的所有注释。但是,当您刷新时,所有注释都会以正确的顺序重新显示,包括对相关评论进行的编辑

0 个答案:

没有答案