2012-02-28 80 views
0

我目前有一个评论部分,仅在整个页面刷新后发布。尽管在页面刷新页面之后,整个页面刷新效率并不高。我想知道是否有人可以帮助我一个js文件,只会刷新部分,我仍然与我的js shakey。任何帮助深表感谢!谢谢!Rails:部分刷新评论部分的jQuery Ajax问题

这是我对create.js当前JS:

$("#comments").html("<%= escape_javascript(render(:partial => @micropost.comments)) %>");

评论控制器

class CommentsController < ApplicationController 
    def create 
    @micropost = Micropost.find(params[:micropost_id]) 
    @comment = @micropost.comments.build(params[:comment]) 
    @comment.user_id = current_user.id 
    @comment.save 
     respond_to do |format| 
     format.html 
     format.js 
    end 
    end 
end 

注释部分

<div id='CommentContainer-<%= micropost.id%>' class='CommentContainer Condensed2'> 
<div class='Comment'> 
<%= render :partial => "comments/form", :locals => { :micropost => micropost } %> 
</div> 
<div id='comments'> 
<%=render micropost.comments %> 
</div> 
</div> 

回答

1

你应该在你的控制器中使用这样的东西。这将根据需要触发js和html模板。

class CommentsController < ApplicationController 
    respond_to :html 
    respond_to :js, only: [ :create ] 

    def create 
    # ... 
    respond_with @comment if @comment.save 
    end 

    def index 
    @comments = Microcomment.find(params[:id]).comments 
    respond_with @comments 
    end 
end 

那么这将需要的意见/评论/ create.js用一些模棱两可的话:

// create.js.erb 
$("#comments").get("/api/micropost/<%= @micropost.id %>/comments"); 

而对于评论的观点将是index.html.erb

# index.html.erb 
<% @comments.each do |comment| %> 
    <!-- Display your comment here --> 
<% end %> 

现在你必须做的是在您的路线中为/api/micropost/:id/comments设置一个match,然后这可以提供所需html格式的评论列表。

请注意,这不是完全安宁的,但我喜欢在那里保留/api来区分来自xhr在url级别的调用。

+0

这种方法似乎在做它总是这样做的事情,现在它刷新整个页面并进入'http:// localhost:3000/microposts/21/comments'并且不会回到原始页面 – Kellogs 2012-02-28 18:31:28