Best practices for loading page content via AJAX request in Rails3?

后端 未结 4 482
醉酒成梦
醉酒成梦 2021-01-31 21:35

Suppose you have a page with two columns of content. For whatever reason, you wish to retrieve the HTML content of one of those columns after the page has loaded, via an AJAX re

4条回答
  •  终归单人心
    2021-01-31 21:57

    I think what I originally outlined is actually the best approach.

    First put an empty, placeholder div in your main view

    and then add a little jQuery to the page

    $.ajax({
        url: "/posts/recent",
        cache: false,
        success: function(html){
          $("#recent_posts").append(html);
        }
    });
    

    and have the action that responses to /posts/recent 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.

    # posts_controller.rb
    def recent
      @recent_posts = #whatever
      render :layout => false
    end
    

    This would render the template in views/posts/recent.html.erb and then the jQuery will take care of inserting the rendered contents into your placeholder div.

提交回复
热议问题