jquery - 为什么这个ajax请求用新提交的评论替换了我所有的评论?

标签 jquery ruby-on-rails ruby ajax ruby-on-rails-3

所以我有这个表单,它在提交评论时请求 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("'",'&apos;').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/

相关文章:

ruby-on-rails - wicked_pdf_image_tag 在查找图像时解析为公共(public)文件夹

ruby-on-rails - 如何将样式添加到 form_for 中的单个输入

ruby - 重构对 Ruby 的 RestClient 的 CURL 请求

javascript - jquery "listview"和图表

jquery - jQuery Galleria-如何将youtube视频标题添加到自动播放

ruby-on-rails - 接受 has_many 关系的嵌套属性

ruby-on-rails - 通过实际示例了解 BDD

javascript - Cmd + B 组合键与 jQuery

javascript - JW Player - 使用事件处理程序停止(目标)多个玩家

ruby - MacRuby 应用程序中的拖动事件问题