1

我有一个包含一堆物品的容器的部分。如果我通过 ajax 添加一个项目,我想在这个容器中反映它而不刷新页面。我在寻找一种 jquery/ajax 方式来刷新页面上的那个部分时遇到问题。我相信有一个简单的方法我只是想念它。

4

1 回答 1

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.
于 2012-12-30T19:49:25.653 回答