You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JQuery AJAX success事件未触发,评论请求始终处于pending状态

AJAX创建评论请求Pending问题

我正在开发一款社交媒体Web应用,通过AJAX实现动态添加帖子与评论功能。目前帖子可正常添加,但评论创建失败——AJAX的success和error事件均未触发,开发者工具显示评论请求始终处于pending状态。

AJAX调用类代码(问题位于createComment方法)

class PostComments{
    // constructor is used to initialize the instance of the class whenever a new instance is created
    constructor(postId){
        this.postId = postId;
        this.postContainer = $(`#post-${postId}`);
        this.newCommentForm = $(`#post-${postId}-comments-form`);

        this.createComment(postId);

        let self = this;
        // call for all the existing comments
        $(' .delete-comment-button', this.postContainer).each(function(){
            self.deleteComment($(this));
        });
    }


    createComment(postId){
        let pSelf = this;
        this.newCommentForm.submit(function(e){
            e.preventDefault();
            let self = this;

            $.ajax({
                method: 'post',
                url: '/comments/create',
                data: $(self).serialize(),
                success: function(data, textStatus, xhr){
                    console.log(data);
                    let newComment = pSelf.newCommentDom(data.data.comment, data.data.comment_user);
                    $(`#post-comments-${postId}`).prepend(newComment);
                    pSelf.deleteComment($(' .delete-comment-button', newComment));

                    new Noty({
                        theme: 'nest',
                        text: "Comment published!",
                        type: 'success',
                        layout: 'topRight',
                        timeout: 1500
                        
                    }).show();

                }, 
                error: function(error){
                    console.log(error.responseText);
                }
            });
        });
    }


    newCommentDom(comment, comment_user){
        // I've added a class 'delete-comment-button' to the delete comment link and also id to the comment's li
        return $(`<li id="comment-${ comment._id }">
                        <p>
                            
                            <small>
                                <a class="delete-comment-button" href="/comments/destroy/${comment._id}">X</a>
                            </small>
                            
                            ${comment.content}
                            <br>
                            <small>
                                ${comment_user}
                            </small>
                        </p>    

                </li>`);
    }

    deleteComment(deleteLink){
        $(deleteLink).click(function(e){
            e.preventDefault();

            $.ajax({
                method: 'get',
                url: $(deleteLink).prop('href'),
                success: function(data){
                    $(`#comment-${data.data.comment_id}`).remove();

                    new Noty({
                        theme: 'nest',
                        text: "Comment Deleted",
                        type: 'success',
                        layout: 'topRight',
                        timeout: 1500
                        
                    }).show();
                },
                error: function(error){
                    console.log(error.responseText);
                }
            });

        });
    }
}

评论创建控制器代码

module.exports.create = async function(req, res){

    try{
        let post = await Post.findById(req.body.post);

        if (post){
            let comment = await Comment.create({
                content: req.body.content,
                post: req.body.post,
                user: req.user._id
            });

            post.comments.push(comment);
            post.save();

            let comment_user = await Comment.find(comment._id).populate('user');

            if (req.xhr){
                return res.status(200).json({
                    data: {
                        comment: comment,
                        comment_user: comment_user.user.name
                    },
                    message: "Comment created!"
                });
            }


            req.flash('success', 'Comment published!');

            res.redirect('/');
        }
    }catch(err){
        req.flash('error', err);
        return;
    }
}

EJS视图代码

posts.ejs

<li id="post-<%= post._id %>">
    <p>
        <% if (locals.user && locals.user.id == post.user.id){ %>
        <small>
            <a class="delete-post-button" href="/posts/destroy/<%= post.id %>">X</a>
        </small>
        <% } %>
        <%= post.content %>
        <br>
        <small>
            -<%= post.user.name %>
        </small>
    </p>
    <div class="post-comments">
        <% if (locals.user){ %>
            <!-- let's give an id to the new comment form, we'll also need to make the same changes in home_posts.js where we're adding a post to the page -->
            <form id="post-<%= post._id %>-comments-form" action="/comments/create" method="POST">
                <input type="text" name="content" placeholder="Add Comment..." required>
                <input type="hidden" name="post" value="<%= post._id %>" >
                <button type="submit">Add</button>
            </form>
        <% } %>
        <div class="post-comments-list">
            <ul id="post-comments-<%= post._id %>">
                <% for (comment of post.comments){%>
                    <%- include('_comment') -%>
                <%} %>
            </ul>
        </div>
    </div>
</li>

comments.ejs

<li id="comment-<%= comment._id %>">
        <p>
            <% if(locals.user && (locals.user.id == comment.user.id || locals.user.id == post.user.id)){ %>
            
            <small>
                <a class="delete-comment-button" href="/comments/destroy/<%= comment.id %>">X</a>
            </small>
            <% } %>
            <%= comment.content %>
            <br>
            <small>
                <%= comment.user.name %>
            </small>
        </p>    

</li>

经排查,评论请求始终处于pending状态。

内容的提问来源于stack exchange,提问作者Kartik Gandhi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 04:31:31