所以我有这个表单,它在提交评论时请求 JS 调用:
<%= simple_form_for([@video, @video.comments.new], :remote => true) do |f| %>
<%= f.association :comment_title, :collection => @video.comment_titles, :label => "Comment Title:", :include_blank => false %>
<%= f.input :body, :label => false, :placeholder => "Post a comment." %>
<%= f.button :submit, :value => "Post" %>
<% end %>
它在评论 Controller 中调用这个创建操作:
def create
@comment = @video.comments.new(params[:comment].merge({:user_id => current_user.id}))
if @comment.save
respond_to do |format|
format.html { redirect_to :back }
format.js
end
else
respond_to do |format|
format.html { redirect_to :back, :alert => "Unable to add comment." }
format.js { render 'fail_create.js.erb' }
end
end
end
渲染这个 create.js.erb 文件:
$(".comment_content").html('<%= escape_javascript(render(@comment)) %>');
$(".comment_form")[0].reset();
上面的 create.js.erb 文件将注释部分渲染到这个文件中:
<% comment_title.comments.each do |comment| %>
<div class="comment_content">
<%= render comment %>
</div>
<% end %>
为什么我的所有评论都被这个 AJAX 请求中新提交的评论所取代?
这是我的部分评论:
<%= link_to image_tag(comment.user.profile.photo.url(:tiny)), profile_path(comment.user.profile), :class => "comment_image" %>
<div class="textual_comment_content">
<div class="comment_text">
<span class="name_link">
<%= link_to "#{comment.user.name}", profile_path(comment.user.profile), :class => "normal" %>
</span>
<%= comment.body.gsub("'",''').html_safe %>
</div>
<span class="comment_footer">
<ul>
<li class="list_style"><%= time_ago_in_words(comment.created_at) %> ago</li>
<% unless current_user != comment.user %>
<li><%= link_to "Delete", video_comment_path(:video_id => @video, :id => comment), :method => :delete, :class => "normal" %></li>
<% end %>
</ul>
</span>
</div>
最佳答案
首先您需要将包装 div 从第一个代码移动到部分代码:
<div class="comment_content">
</div>
然后只需在第一个/最后一个元素之前/之后插入 html:
$(".comment_content:first").before('<%= escape_javascript(render(@comment)) %>');
$(".comment_content:last").after('<%= escape_javascript(render(@comment)) %>');
关于jquery - 为什么这个ajax请求用新提交的评论替换了我所有的评论?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5585336/