通过在Rails3 AJAX请求的最佳实践加载网页内容? [英] Best practices for loading page content via AJAX request in Rails3?

查看:119
本文介绍了通过在Rails3 AJAX请求的最佳实践加载网页内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有与内容两列的页面。不管什么原因,你要检索的页面加载后,这些列之一的HTML内容,通过Ajax请求。用户不需要采取行动,以使内容负荷(无链接单击或表单提交),它只是自动发生。

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 request. The user does not need to take an action to make the content load (no link clicking or form submissions), it just happens automatically.

我可以很容易地通过在主响应返回一个空的占位符的div做到这一点

I can easily do this by returning 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/pink",
    cache: false,
    success: function(html){
      $("#pink-dancing-elephants").append(html);
    }
});

和有反应/大象/舞蹈/粉红返回HTML相应的BLOB的操作。

and have the action that responses to /elephants/dancing/pink return the corresponding blob of HTML.

这一切工作正常,但我想知道如果我错过了一些Rails3功能,这将使这更容易。例如。我在寻找能够为只是把像在主视图下的能力,并有它的其余部分发生的神奇

This all works fine, but I'm wondering if I'm missing some Rails3 feature that would make this easier. E.g. I'm searching for the ability to be able to just put something like the following in the main view and have the rest of it happen by "magic"

<%= render :url=>"/elephants/dancing/pink", :remote => true %>

我缺少的东西?

Am I missing something?

推荐答案

我想我本来概述其实是最好的办法。

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

先放一个空的占位符格在你的主视图

First put an empty, placeholder div in your main view

<div id="recent_posts"></div>

,然后加少许的jQuery的页面

and then add a little jQuery to the page

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

和有反应/职位/最近返回的HTML,你想拥有填补了DIV的BLOB的操作。在一个由AJAX请求调用的操作,你要渲染:布局=>假,以保持HTML返回的BLOB从包括整个框架。例如,

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

这将使在意见/职位/ recent.html.erb模板,然后jQuery将采取插入的内容呈现到您的占位符格的照顾。

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.

这篇关于通过在Rails3 AJAX请求的最佳实践加载网页内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆