2012-03-02 69 views
6

我有一個標籤頁,我只想通過Ajax呈現不同的諧音,當標籤被點擊時。我有一些代碼,但我不認爲這是最有效的方法。我希望如果任何人都可以用我已經存在的代碼來幫助我,或者如果有更簡單的方法,我會很感激。謝謝!的Rails:渲染局部模板通過Ajax

HTML標籤

<li class='StreamTab StreamTabRecent active'> 
<%= link_to 'Most Recent', mostrecent_schools_path, :remote => true, :class => 'TabText' %> 
</li> 


<div id='ContentBody'> 
<div id='ajax'></div> 
<%= render 'users/microposts', :microposts => @microposts %> 
</div> 

學校控制器

class SchoolsController < ApplicationController 
    def mostrecent 
    @school = School.find_by_slug(request.url.gsub('http://localhost:3000/','')).id 
    @microposts = @user.microposts.order('created_at DESC').paginate(:per_page => 3, :page => params[:page]) 
    respond_to do |format| 
     format.html 
     format.js 
    end 
    end 
end 

最近JS

$("#ContentBody").html('<%= escape_javascript(render :partial => "users/microposts")%>'); 

路線

resources :schools do 
    collection do 
     get :mostrecent 
    end 
    end 
+0

「我有一些代碼,但我不認爲這是最有效的方式」。上述代碼是否正常工作?你想優化這個過程,或者你想要一個工作代碼? – prasvin 2012-03-02 05:34:35

+0

@prasvin該代碼不工作,試圖讓它從我的東西之前在互聯網上找到工作,但我不知道如何得到它去,或者如果它是最有效的方式。如果有這樣做的更好的辦法,我所有的耳朵學習:) – Kellogs 2012-03-02 05:36:53

回答

10

查看我對上一篇文章的回答。這會給你一個想法AJAX in Rails: Show model#new form after completing a model#update

你可以做的是呈現在行動JSON,並通過部分爲JSON。

def mostrecent 
    @school = School.find_by_slug(request.url.gsub('http://localhost:3000/','')).id 
    @microposts = @user.microposts.order('created_at DESC').paginate(:per_page => 3, :page => params[:page]) 
    respond_to do |format| 
    format.json { render :json => {:success => true, :html => (render_to_string 'users/microposts')} } 
    format.html { } 
    end 
end 

可以訪問在JS的JSON(即一個JavaScript/CoffeeScript的文件如mostrecent.js或mostrecent.js.coffee)和替換的當前元素。

$('.TabText').live 'ajax:success', (event,data) -> 
    $('#ContentBody').html(data.html) if(data.success == true) 
+0

我欣賞這非常:) – Kellogs 2012-03-02 05:50:38

+1

寫足夠回來,如果上述方法不工作,或者你不知道的東西。代碼未經測試,但幾乎可以讓你接近完成任務。 – prasvin 2012-03-02 05:55:03

+0

我從來沒有使用JSON,但我的圖像,而不是一個JS文件我創建一個JSON文件,並將其添加到它? – Kellogs 2012-03-02 05:58:11

2

Prasvin的答案是點亮的。返回並執行JS可能看起來很簡單,但它會使調試更加糟糕 - 如何在通過AJAX返回的JS中設置斷點?相反,你應該在頁面中包含所有的JS,並只發送數據。

0

我使用軌道4.2和@prasvin回答我指出了正確的方向,但是當我用

format.json { render :json => {:success => true, :html => (render_to_string 'instruments')} } 

我會得到一個錯誤「缺少模板......儀器...」

經過一番閱讀,我發現這個評論rails render_to_string giving errors with partial view。 @marcel提到你需要指定文件是部分,部分:'文書',如下:

format.json { render :json => {:success => true, :html => (render_to_string partial: 'instruments')} }