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

时间:2009-06-20 00:09:11

标签: jquery ruby-on-rails ajax

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

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

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

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

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

3 个答案:

答案 0 :(得分:4)

如果您使用的是更新版本的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文件一样,你在相关视图文件夹中有一个类似的first_method.js.erb文件 您的index.html.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突出显示的其他每个更长的方法再次重复相同的过程。

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

希望这有帮助!

答案 1 :(得分:0)

你需要使用ajax。

http://docs.jquery.com/Ajax

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

一个例子:

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

答案 2 :(得分:0)

假设您安装了jRails plugins

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视图中。

<h1>Index</h1>

<div id="index">First section here.</div>
<div id="second">Second section here.</div>
<div id="third">Third section here.</div>

<%= remote_function(:action => "long_section", :update => "second") %>
<%= remote_function(:action => "very_long_section", :update => "third") %>