2012-02-28 2 views
0

현재 전체 페이지가 새로 고쳐진 후에 만 ​​게시되는 덧글 섹션이 있습니다. 게시물 이후에 페이지 자체가 새로 고쳐지기는하지만 전체 페이지를 새로 고치는 데 비효율적입니다. 누가 그 부분을 새로 고칠 js 파일로 나를 도울 수 있는지 궁금 해서요, 나는 아직도 내 js와 흔들리고 있습니다. 어떤 도움을 많이 주시면 감사하겠습니다! 고맙습니다!레일 : 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이 필요합니다 : 이제 모든 당신을 index.html.erb

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

될 것

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

그리고 의견보기 해야 할 일은 /api/micropost/:id/comments에 대해 match을 설정하고 원하는 html 형식의 설명 목록을 제공 할 수 있습니다.

이것은 완전히 편안하지는 않지만, URL 수준에서 xhr에서 오는 전화를 구분하기 위해 /api을 계속 유지하려고합니다.

+0

이 방법은 항상 전체 페이지를 새로 고치고 http : // localhost : 3000/microposts/21/comments'로 이동하여 원래 페이지로 돌아 가지 않습니다. – Kellogs