Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

jquery - How to asynchronously load a partial page in rails

In creating a ruby on rails / jquery app, there's a part of a page that is time-consuming to generate.

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):

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

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

and the partial will use some parts @org to generate some content (hitting another external REST service).

app/views/sample/_calculate.html.erb

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

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...

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First put an empty, placeholder div in the main response

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

and then add a little jQuery to the page

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

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

This would render the template in views/elephants/dancing.html.erb.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...