我正在尝试使用 javascript 和 ajax 将新评论附加到现有评论列表中。我设置了 Comments#create 来创建新评论,然后呈现其文本。但是我怎样才能用ajax访问这个文本呢?
controllers/comments_controller.rb
def new
@comment = Comment.new
@comments = Comment.all
end
def create
@thing = Thing.find(params[:thing_id])
@comment = @thing.comments.create(comment_params)
render text: @comment.text.to_s + "".html_safe
end
我的新评论和 ajax/javascript 尝试表单:
<%= form_for([@thing, @comment], remote: true) do |f| %>
<%= f.text_area :text, :placeholder => "Explain your rating..." %>
<div id="btn"><%= f.submit "Post", class: "btn", id: "postacomment" %></div>
<script type="text/javascript">
$("#postacomment").click(function() {
$.get( "<%= new_thing_comment_path(:id => @comment.id) %>", function( data ) {
$('#comments_h2').prepend( data );
});
});
</script>
<% end %>
最佳答案
首先,不要尝试改变 HTTP 方法来满足您的需求,而是遵循它们。
如果你想用rails响应javascript,那是相当简单的。在您的评论 Controller 上:
def new
@comment = Comment.new
@comments = Comment.all
end
def create
@thing = Thing.find(params[:thing_id])
@comment = @thing.comments.create(comment_params)
respond_to do |format|
format.html { redirect_to new_comments_path } #this is just a redirection in case JS is disabled
format.js
end
end
正如您所看到的,我们现在响应两种类型的格式,在本例中为 html
和 js
,这迫使您拥有相应的 View ,或者至少对于 js
版本,可能如下所示:
app/views/comments/create.js.erb:
$('#comments_h2').prepend("<%= j @comment %>");
在上面的示例中,我假设您有一个用于呈现评论的部分内容,它应该类似于:
app/views/comments/_comment.html.erb:
<h2><%= comment.content %></h2>
显然,您必须更新该文件才能满足您的需求。
希望对你有帮助!
关于javascript - rails : Can I send a GET request to a create path?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27413565/