2012-02-28 76 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