我正在构建一个社交媒体网络应用程序,并试图通过AJAX动态添加帖子和 comments .正在成功添加帖子,但未添加 comments ,因为未触发成功事件.即使是错误事件也没有被激发.但是AJAX调用正在完成(我通过在调用之前、成功事件和错误事件中以及调用之后添加console.log语句来判断它).

以下是我编写的代码:

这是使用类启动AJAX调用的代码(问题出在createComment方法中,其余代码用于引用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;
    }
}

这是我的帖子和 comments 视图部分:-

Posts.ej

<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 request screenshot

推荐答案

问题已经解决了.在控制器操作中,我编写了Comment.find(comment._id),而不是Comment.findById(comment._id),这就是为什么由于等待关键字,它永远挂起,成功回调没有触发.

Jquery相关问答推荐

使用 JQuery 在 span 标签中用逗号分隔页面上的文本

jQueryUI 模态对话框不显示关闭按钮 (x)

jQuery中的多个 Select 器链接?

jquery克隆div并将其附加在特定div之后

在文本框中的最后一个字符之后设置焦点

组合数组时无法读取未定义的属性推送

可以在不使用for=id的情况下将标签与复选框相关联吗?

为什么要两次声明 jQuery?

使html文本输入字段随着我输入而增长?

为不同的 node 类型配置jstree右键上下文菜单

使用 jQuery 按字母顺序对选项元素进行排序

带有函数的 JavaScript 三元运算符示例

在jQuery中获取CSS规则的百分比值

Fancybox 不适用于 jQuery v1.9.0 [ f.browser 未定义 / 无法读取属性 'msie' ]

如何获得两个日期对象之间的小时差?

Chrome 中的 AJAX 发送选项而不是 GET/POST/PUT/DELETE?

什么时候应该使用 jQuery 的 document.ready 函数?

删除所有以某个字符串开头的类

jQuery中的wait()或sleep()函数?

jQuery 将换行符转换为 br (nl2br 等效)