Rails, rendering partial via JS on page load?
So I understand how to get partials to render when say a link is clicked, but say I开发者_运维知识库 want to start loading the partial after the page renders?
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.
Controller
def weather
slow_api_request
respond_to do |format|
format.js {render :layout => false}
end
end
But so then how can I start the request for the partial after the page loads (because the action is pretty slow to retrieve the data from the API), I'm using rails UJS, I just a bit confused.
You should simply add an ajax
call. Assuming you're using jQuery, just add this kind of scripts in your view:
$.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)
}
});
精彩评论