JQuery AJAX成功事件未触发。

huangapple go评论82阅读模式
英文:

JQuery AJAX success event not firing

问题

我正在构建一个社交媒体Web应用,尝试通过Ajax动态添加帖子和评论。帖子成功添加,但评论没有添加,因为成功事件没有触发。甚至错误事件也没有触发。但是AJAX调用已经完成(我通过在调用之前、成功事件和错误事件之后添加console.log语句来检查)。

以下是我编写的代码:这是使用类来初始化AJAX调用的代码(问题出现在createComment方法中,其余的代码是用于参考createComment中使用的其他方法):

class PostComments {
    // 构造函数用于在创建新实例时初始化类的实例
    constructor(postId) {
        this.postId = postId;
        this.postContainer = $(`#post-${postId}`);
        this.newCommentForm = $(`#post-${postId}-comments-form`);

        this.createComment(postId);

        let self = this;
        // 调用所有现有的评论
        $('.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) {
        // 我已经为删除评论链接添加了一个类“delete-comment-button”,还为评论的li添加了id
        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;
    }
}

这是我的帖子和评论视图的部分:

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){ %>
            <!-- 给新评论表单一个id,我们还需要在home_posts.js中做相同的更改,因为我们在页面上添加了一个帖子 -->
            <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>

编辑:我在开发工具中检查了请求,发现它一直保持挂起状态。

英文:

I am building a social media web app and trying to add posts and comments dynamically via ajax. The posts are being added successfully but comments are not being added because the success event isn't firing. Even error event is not being fired. But the AJAX call is being completed (I checked it by adding console.log statements before call, in the success event and error event and after the call).

Here is the code that I wrote:-

This is the code for initiating AJAX call using classes (The problem is in createComment method, rest of the code is for reference to other methods used in 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
$(&#39; .delete-comment-button&#39;, this.postContainer).each(function(){
self.deleteComment($(this));
});
}
createComment(postId){
let pSelf = this;
this.newCommentForm.submit(function(e){
e.preventDefault();
let self = this;
$.ajax({
method: &#39;post&#39;,
url: &#39;/comments/create&#39;,
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($(&#39; .delete-comment-button&#39;, newComment));
new Noty({
theme: &#39;nest&#39;,
text: &quot;Comment published!&quot;,
type: &#39;success&#39;,
layout: &#39;topRight&#39;,
timeout: 1500
}).show();
}, 
error: function(error){
console.log(error.responseText);
}
});
});
}
newCommentDom(comment, comment_user){
// I&#39;ve added a class &#39;delete-comment-button&#39; to the delete comment link and also id to the comment&#39;s li
return $(`&lt;li id=&quot;comment-${ comment._id }&quot;&gt;
&lt;p&gt;
&lt;small&gt;
&lt;a class=&quot;delete-comment-button&quot; href=&quot;/comments/destroy/${comment._id}&quot;&gt;X&lt;/a&gt;
&lt;/small&gt;
${comment.content}
&lt;br&gt;
&lt;small&gt;
${comment_user}
&lt;/small&gt;
&lt;/p&gt;    
&lt;/li&gt;`);
}
deleteComment(deleteLink){
$(deleteLink).click(function(e){
e.preventDefault();
$.ajax({
method: &#39;get&#39;,
url: $(deleteLink).prop(&#39;href&#39;),
success: function(data){
$(`#comment-${data.data.comment_id}`).remove();
new Noty({
theme: &#39;nest&#39;,
text: &quot;Comment Deleted&quot;,
type: &#39;success&#39;,
layout: &#39;topRight&#39;,
timeout: 1500
}).show();
},
error: function(error){
console.log(error.responseText);
}
});
});
}
}

This is the code of my controller action for creating comments:-

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(&#39;user&#39;);
if (req.xhr){
return res.status(200).json({
data: {
comment: comment,
comment_user: comment_user.user.name
},
message: &quot;Comment created!&quot;
});
}
req.flash(&#39;success&#39;, &#39;Comment published!&#39;);
res.redirect(&#39;/&#39;);
}
}catch(err){
req.flash(&#39;error&#39;, err);
return;
}
}

This is my posts and comments view partials:-

posts.ejs

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

comments.ejs

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

Edit:- I inspected the request in developer tools and found out that it remains pending forever

Pending request screenshot

答案1

得分: 0

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

英文:

The problem has been solved. In controller action, I had written Comment.find(comment._id) instead of Comment.findById(comment._id) which is why due to await keyword it was pending forever and the success callback wasn't firing.

huangapple
  • 本文由 发表于 2023年1月7日 23:13:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75041420.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定