我试图将我的评论保存在ajax中,以使页面不会重新加载。这是我到目前为止所做的,但是没有用。
我该如何工作?
在我的查看文件中
<%= form_for [@book, inspiration, @comment], :html => { :class => "comment-form" } do |f| %>
<%= f.text_field :content, placeholder: "Add a comment & hit enter.", :id => 'comment_submit' %>
<% end %>
同样在该文件中,我包括了:
<script>
$(document).on('keypress', '#comment_submit', function(event) {
if ( event.which == 13 ) {
event.preventDefault();
var myData = $( "form" ).serialize();
$.ajax({
type: "POST",
data: myData,
url: <%= inspiration_comments_path(inspiration) %>,
success: function(data){
if(data){
alert('success')
}
}
});
}
});
</script>
评论应该仅通过按回车键提交。没有按钮。
困难的另一个方面,这些评论是关于书的。这些书全部显示在页面上,当您单击一本书时,它会在注释部分打开一个模式,其中包含有关该模式的信息。我尝试为id选择器指定一个动态名称,但是页面加载没有任何改变。
谢谢你的帮助。
最佳答案
Rails具有built in support for Ajax。您不必编写自己的jQuery即可提交评论。在remote: true
中使用form_for
选项,Rails会为您处理。但是,您将必须编写一个JavaScript处理程序,并确保您的控制器以JavaScript响应。
例如:
<%= form_for [@book, inspiration, @comment], remote: true do |f| %>
# ...
然后,您的控制器将具有以下内容:
def create
@comment = Comment.new(comment_params)
@comment.save
respond_to do |format|
format.html # default without js
format.js # make sure you have a create.js.erb that will handle updating the dom
end
end
然后,您将要创建一个
comments/create.js.erb
处理程序。该处理程序将具有必要的JavaScript,以处理dom的更新,例如插入注释。请查看Rails Guides以获取更多信息。
关于javascript - 如何在Rails 4上获取Ajax注释,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26266527/