gpt4 book ai didi

javascript - Rails 使用 AJAX 删除评论

转载 作者:行者123 更新时间:2023-12-03 02:01:00 25 4
gpt4 key购买 nike

我在使用 AJAX 删除评论时遇到问题。当我删除评论时,页面上没有任何反应,直到刷新,但数据库中的数据被删除。我搜索这个主题超过 2 个小时,但仍然找不到答案。

浏览次数:

#annoucements/show.html.haml
=render @comments

#comments/_comment.html.haml
%ul
%p
%b User:
= comment.user.username
= time_ago_in_words(comment.created_at)
%p
%b Content:
= comment.content
- if comment.user.id == current_user[:id]
= link_to 'Delete comment', annoucement_comment_path(@annoucement, comment), method: :delete, data: {confirm: 'Are you sure?'}, remote: true

Controller :

#comment_controller.rb
def destroy
@annoucement = Annoucement.find(params[:annoucement_id])
@comment = Comment.find(params[:id])
@comment.destroy

respond_to do |format|
format.html { redirect_to @annoucement }
format.js
end
end

JS:

#destroy.js.erb

$('#comment_<%= @comment.id %>').remove();

控制台:

Started DELETE "/annoucements/9/comments/142" for 127.0.0.1 at 2018-04-26 01:11:53 +0200
Processing by CommentsController#destroy as JS
Parameters: {"annoucement_id"=>"9", "id"=>"142"}
Comment Load (0.2ms) SELECT "comments".* FROM "comments" WHERE "comments"."id" = ? LIMIT ? [["id", 142], ["LIMIT", 1]]
Annoucement Load (0.1ms) SELECT "annoucements".* FROM "annoucements" WHERE "annoucements"."id" = ? LIMIT ? [["id", 9], ["LIMIT", 1]]
CACHE Comment Load (0.0ms) SELECT "comments".* FROM "comments" WHERE "comments"."id" = ? LIMIT ? [["id", 142], ["LIMIT", 1]]
(0.1ms) begin transaction
SQL (0.3ms) DELETE FROM "comments" WHERE "comments"."id" = ? [["id", 142]]
(82.4ms) commit transaction
Rendering comments/destroy.js.erb
Rendered comments/destroy.js.erb (0.9ms)
Completed 200 OK in 95ms (Views: 5.7ms | ActiveRecord: 82.9ms | Solr: 0.0ms)

最佳答案

你的js正在尝试删除id为@comment_XXX的元素(XXX是被删除评论的id)。但你还没有设置这个id。将其添加到包含评论的 div

%ul{:id => "comment_#{comment.id}"}
%p
%b User:
= comment.user.username
= time_ago_in_words(comment.created_at)
etc...

关于javascript - Rails 使用 AJAX 删除评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50032668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com