使用Jquery在Rails 3中使用Ajax刷新部分

时间:2012-12-30 19:47:05

标签: ruby-on-rails ruby ajax jquery

我有一个部分有一个包含一堆项目的容器。如果我通过ajax添加一个项目,我想在没有刷新页面的情况下在这个容器中反映出来。我有一个问题是找到一个jquery / ajax方法来刷新页面上的那个部分。我确信有一种简单的方法我只是错过了它。

1 个答案:

答案 0 :(得分:3)

<强> .js.erb

$('#container_id').html('<%= escape_javascript(render(:partial => "partial", :formats => [:html])) %>');

完整示例:

# CommentsController

def refresh_comments
  @comments = Comment.last_in(10.second) # fetch collection
  respond_to do |format|
    format.html { } # by default renders views/comments/refresh_comments.html.erb as template
    format.js { } # by default renders views/comments/refresh_comments.js.erb as template
  end
end

# views/comments/refresh_comments.js.erb

$('#post_comments').html('<%= escape_javascript(render(:partial => "comments_thread", :formats => [:html])) %>');

# * where: "post_comments" - is a DOM id of container.
#          "comments_thread" - name of partial. :formats => [:html] says that you render _comments.html.erb

# Look JQuery API for details.