如何在不刷新页面的情况下发表评论。,

时间:2017-07-31 10:57:25

标签: ruby-on-rails-4

我希望用户能够在没有浏览器刷新整个页面的情况下发表评论

现在评论已经提交了,但我面临的问题是,在用户提交评论后,页面和用户在表单中放置的内容仍然存在,我希望它能够正确提交,还有用户表格成功提交后,输入应清除。

我的控制器操作

def create
    @post = Post.find(params[:post_id])
    @comment = @post.comments.new(comment_params)


    @comment.user = current_user
    if @comment.save
        respond_to do |format|
            flash[:notice] = "Successfully created a comment"
            format.json { render json: @post }
        end
    else
        redirect_to :back
    end
end

我的观点

<div class="header-wrapper-blog">
  <div class="heading_for_blog">
    <div class="container">
      <%= simple_form_for([@post, @post.comments.build], remote: true, :html => {:multipart => true, id: "newcomment"  } ) do |f| %>
        <%= f.input :body, as: :text %>
        <button type="submit" class="btn btn-success" id="comment-form" name="submit"/>Submit</button>
      <% end %>
    </div>
  </div>
</div>

我当前的Ajax代码

$(function(){
  $("#newcomment").on("submit", function(event){


  $.ajax({
      type: "POST",
      url: this.action,
      data: $(this).serialize(),
      success: function(response) {
        //update the DOM
      }
    });
    event.preventDefault();
  });
})

1 个答案:

答案 0 :(得分:0)

首先,如果你使用的是remote: true,那么就不需要触发你正在做的另一个ajax事件。 所以现在你有两种情况,A.With remote: true B.With触发Ajax。

从控制器中删除format.json { render json: @post }行,rails将在各自的控制器视图中呈现文件create.js.erb。在该文件中,您可以编写逻辑来清除该表单或更新特定的div。 对于Ex。 $(#newcomment).reset();您可以更新div,例如$(#div).html("blah");

B.如果您从表单中删除了remote: true,那么您可以使用您提到的ajax,但在这种情况下添加dataType: script,它将呈现相同的create.js.erb

C.如果您不想遵循上述方法,那么您可以在成功回调ajax时调用此行$(#newcomment).reset();;