如何通过ruby on rails action方法使用JQuery从数据库加载内容?

我有一个页面需要从数据库和可能的其他来源提取内容。

这就是我在rails应用程序上构建ruby的方法。

/ Index – 这有三个不同的部分,需要加载三种不同类型的内容。 每个人都会花费不同的时间来返回,因此我想在我为每个div播放时显示加载消息以填充数据。

要加载数据,理想情况下我想在我的控制器上调用Ruby方法然后渲染部分。

我已经进行了搜索,但我无法看到如何加载页面索引,然后从操作方法加载数据作为单独的操作。

如果您使用的是更新版本的Rails,并希望以尽可能不引人注目的方式执行此操作,则可以在控制器中使用:respond_to选项,如下所示:

class MyController < ApplicationController def first_method respond_to do |format| format.html # this handles normal requests asking for html format.js # this handles requests asking for javascript to be sent instead end end end 

如果您对单击进行响应,则可以执行类似于在页面上触发查询的操作

 $("a.element_you_click_to_trigger").click(function(e) { e.preventDefault(); // make sure clicking doesn't trigger unneeded event bubbling $.ajax({url: "/controller/first_method", type: "POST", dataType: "script"}); // send a request and tell the server that you want javascript back } 

就像您在该控制器的views文件夹中有一个index.html.erb文件一样,您在index.html.erb文件first_method.js.erb的相关视图文件夹中有一个类似的first_method.js.erb文件:

 views controller index.html.erb first_method.js.erb 

这将返回获取客户端执行的javascript,但它获取构建服务器端,因此您可以包含rails ERB片段,因此您可以执行以下操作:

 $('#loading_placeholder_element').html('<%= escape_javascript(render(:partial => "create")) %>'); // do some other stuff you fancy in the page // then make the next call once the other stuff is over (you may need to add this as a call back on an animation): $.ajax({url: "/controller/second_method", type: "POST", dataType: "script"}); 

然后,您将再次为fsmf突出显示的其他每个更长的方法重复相同的过程。

我在几个月前学习这个时发现这个关于jQuery的Railscast非常有帮助,我真的推荐它。

希望这可以帮助 !

你需要使用ajax。

http://docs.jquery.com/Ajax

我不知道如何在铁轨上使用ruby或ruby。 但我猜这个概念是一样的。

一个例子:

 $.post("yourAjaxTarget.html",{ //html as an example attribute1: "blabla", attribute2: 1234 }, function(data){ //do something }, "json"); 

假设你安装了jRails插件 。

 class MyController < ApplicationController def index # your main action end def long_section # this method should accept XHR requests # and render the HTML view # long_section.html.erb render :layout => false # or partial end def very_long_section # this method should accept XHR requests # and render the HTML view # very_long_section.html.erb render :layout => false # or partial end end 

在index.html.erb视图中。

 

Index

First section here.
Second section here.
Third section here.
<%= remote_function(:action => "long_section", :update => "second") %> <%= remote_function(:action => "very_long_section", :update => "third") %>