我希望用戶能夠發佈沒有瀏覽器刷新整個頁面的註釋,如何發表評論無需刷新頁面,
對於現在的意見被提交,但是,我所面臨的問題在用戶提交評論後,該頁面以及用戶在表單中放置的任何內容都會保留,我希望它能夠正確提交,並且在成功提交表單後用戶輸入應該清除。
我控制器操作
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();
});
})