Javascript Rails使用AJAX删除注释
我无法使用AJAX删除注释。当我删除注释时,在刷新之前页面上不会发生任何事情,但数据库中的数据会被删除。我搜索这个话题已经两个多小时了,但仍然找不到一个答案 观点:Javascript Rails使用AJAX删除注释,javascript,ruby-on-rails,ajax,Javascript,Ruby On Rails,Ajax,我无法使用AJAX删除注释。当我删除注释时,在刷新之前页面上不会发生任何事情,但数据库中的数据会被删除。我搜索这个话题已经两个多小时了,但仍然找不到一个答案 观点: #annoucements/show.html.haml =render @comments #comments/_comment.html.haml %ul %p %b User: = comment.user.username = time_ago_in_words(comment.created_at)
#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
控制器:
#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:
您的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...
显示您的评论视图谢谢,它正在工作,而不是您给出的详细代码,因为在HAML中它应该是
%ul{:id=>“comment{comment.id}”
,但仍然非常感谢您,这非常有用。
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)
%ul{:id => "comment_#{comment.id}"}
%p
%b User:
= comment.user.username
= time_ago_in_words(comment.created_at)
etc...