如何异步加载在导轨部分页面 [英] How to asynchronously load a partial page in rails
问题描述
在创建上轨/ jQuery的应用程序中的红宝石,有一个网页,很耗时,生成的一部分。
In creating a ruby on rails / jquery app, there's a part of a page that is time-consuming to generate.
我想更改的页面加载,使得大部分的页面加载的向右走,而且一个占位符预留耗时的加载异步,并注入到页面的Ajax / jQuery的时候才完蛋了。
I want to change how the page is loaded so that most of the page loads right away, and a placeholder is reserved for the time-consuming part to load asynchronously, and be injected into the page with ajax / jquery when it is finished.
我现在已经(简体)是什么:
What I have now (simplified):
应用程序/视图/样品/ show.html.erb:
app/views/sample/show.html.erb:
<div id="theResult">
<%= render :partial => 'calculate', :object => @org) %>
</div>
和部分将使用一些地方@org生成一些内容(打另一外部REST服务)。
and the partial will use some parts @org to generate some content (hitting another external REST service).
应用程序/视图/样品/ _calculate.html.erb
app/views/sample/_calculate.html.erb
<%
# code to take org and turn it into content
%>
<!--...html to display results here -->
我知道这很可能打破正常的MVC架构的规则,因为我的部分,似乎有太多的逻辑,想清理一下,以及...
I realize this is probably breaking proper MVC architecture rules since my partial seems to have too much logic, and would like to clean that up as well...
所以我想我有两个问题一:(1)我怎么得到这个工作,和(2)我应该怎么打扫一下遵循良好的红宝石/导轨/ MVC的做法
So I guess I have two questions in one: (1) how do I get this to work, and (2) how should I clean this up to follow good ruby/rails/mvc practices?
推荐答案
先放一个空的占位符格主响应
First put an empty, placeholder div in the main response
<div id="pink-dancing-elephants"></div>
,然后加少许的jQuery的页面
and then add a little jQuery to the page
$.ajax({
url: "/elephants/dancing",
cache: false,
success: function(html){
$("#pink-dancing-elephants").append(html);
}
});
和有反应/大象/舞蹈/粉红返回HTML,你想拥有填补了DIV的BLOB的操作。在一个由AJAX请求调用的操作,你要渲染:布局=>假,以保持HTML返回的BLOB从包括整个框架。例如,
and have the action that responses to /elephants/dancing/pink return the blob of HTML that you want to have fill up the div. In the action that is invoked by the AJAX request, you'll want to render with :layout => false to keep the returned blob of HTML from including the entire frame. E.g.
# elephants_controller.rb
def dancing
@elephants = #whatever
render :layout => false
end
这将使在视图中/大象/ dancing.html.erb的模板。
This would render the template in views/elephants/dancing.html.erb.
这篇关于如何异步加载在导轨部分页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!