如何在rails中异步加载部分页面

时间:2011-07-15 00:46:55

标签: jquery ruby-on-rails ajax

在rails / jquery app上创建ruby时,生成页面的一部分非常耗时。

我想更改页面的加载方式,以便大部分页面立即加载,并且占位符保留用于异步加载的耗时部分,并且当它是ajax / jquery时注入到页面中结束。

我现在所拥有的(简化):

app / views / sample / show.html.erb:

<div id="theResult">
    <%= render :partial => 'calculate', :object => @org) %>
</div>

部分将使用@org的某些部分生成一些内容(点击另一个外部REST服务)。

应用程序/视图/样品/ _calculate.html.erb

<%
    # code to take org and turn it into content
%>
<!--...html to display results here -->

我意识到这可能违反了正确的MVC架构规则,因为我的部分似乎有太多的逻辑,并且想要清理它......

所以我猜我有两个问题:(1)我如何让它工作,(2)我应该如何清理它以遵循良好的ruby / rails / mvc做法?

2 个答案:

答案 0 :(得分:67)

首先在主响应中放置一个空的占位符div

<div id="pink-dancing-elephants"></div>

然后在页面中添加一点jQuery

$.ajax({
    url: "/elephants/dancing",
    cache: false,
    success: function(html){
      $("#pink-dancing-elephants").append(html);
    }
});

并且对/ elephants / dancing / pink的响应返回你想要填充div的HTML的blob。在AJAX请求调用的操作中,您需要使用以下内容进行渲染:layout =&gt; false以保持返回的HTML blob不包含整个框架。 E.g。

# elephants_controller.rb
def dancing
  @elephants = #whatever
  render :layout => false
end

这将在views / elephants / dancing.html.erb中呈现模板。

答案 1 :(得分:10)

与@cailinanne相比,有一种更简单的方法。

使用她的相同示例,但我倾向于使用此技术来更新div,所以我的div首先会有部分:

<div id="pink-dancing-elephants">
   <%= render "elephants/dancing", elephant: some_thing  %>
</div>

然后使用jQuery加载方法:

$("#pink-dancing-elephants").load("/elephants/dancing");

这将返回整个部分。一定要使用layout:false,并可选择设置params。我倾向于使用像这样的部分

# elephants_controller.rb
def dancing
  render "elephants/_dancing", 
         locals: { elephant: some_thing },
         layout: false
end

这将在views / elephants / _dancing.html.erb中呈现模板。

注意控制器方法的部分名称中的下划线以及在视图中调用render时如何不使用它。