我正在尝试使用 ajax 保存我的评论,以便页面不会重新加载。这是我到目前为止所做的,但它不起作用。
我怎样才能让它发挥作用?
在我的 View 文件中
<%= 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 处理程序,并确保您的 Controller 以 JavaScript 进行响应。
例如:
<%= form_for [@book, inspiration, @comment], remote: true do |f| %>
# ...
然后,您的 Controller 将具有如下内容:
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/