2011-05-22 128 views
1

所以我明白如何獲得partials渲染時說一個鏈接被點擊,但說我想開始加載頁面呈現後的部分?Rails,在頁面加載時通過JS渲染部分?

show.html.erb

<div id="weather"></div> 

weather.js.erb

$("#weather").html("<%= escape_javascript(render(:partial => 'weather')) %>"); 

weather.html.erb

<%= Time.now %> # For brevity. This actually does more. 

控制器

def weather 

    slow_api_request 

    respond_to do |format| 
    format.js {render :layout => false} 
    end 
end 

但是這樣的話我怎麼能開始爲頁面加載後的部分請求(因爲動作是檢索來自API的數據很慢),我使用的軌道UJS,我只是有點困惑。

回答

3

您應該簡單地添加一個ajax調用。假設你使用jQuery,只需在你的視圖中添加這種腳本:

$.ajax({ 
    type: "GET", 
    url: "<%= url_for your_path %>" , 
    success: function(data){ 
    //if ever there is something more to do (there is also an error handler) 
    } 
});