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



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

现在评论已提交,但我面临的问题是,在用户提交评论后,页面以及用户放入表单中的任何内容都保留在那里,我希望它正确提交,并且一旦表单成功提交,用户输入应该清除。

我的控制器操作

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();
});
})

首先,如果您使用的是remote: true,那么无需触发您正在执行的另一个 ajax 事件。 所以现在你会有两种情况,A.Withremote: trueB.With 触发 Ajax。

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

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

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

最新更新