简体   繁体   English

rails - 加载另一个页面并替换 div

[英]rails - load another page and replace the div

After some struggling, I managed to make the ajax work:经过一番挣扎,我设法使 ajax 工作:

hello.js.erb:你好.js.erb:

$("#show_hosts").html("some text");

testQueuesController.rb: testQueuesController.rb:

class testQueuesController < ApplicationController

  def index

    @test_queues = testQueue.all

    respond_to do |format|

      format.html

      format.json { render json: @test_queues }

    end

  end

end

The relevant part in the view:视图中的相关部分:

<%= link_to "hello", { :controller => "kashmir_queues", :action => "hello" }, :remote => true %>

Now, this is working, but what I really wanna do, is now load "some text", but to load another view I have named show_hosts.html.erb, how can I do it ?现在,这是有效的,但我真正想做的是加载“一些文本”,但是要加载另一个我命名为 show_hosts.html.erb 的视图,我该怎么做?

If I understand your question correctly you want to render the view called show_hosts.html.erb in the HTML tag with the ID show_hosts .如果我正确理解您的问题,您希望在 ID 为show_hosts的 HTML 标记中呈现名为show_hosts.html.erb的视图。

To be able to do this you would need to create a partial for each host - something like _host.html.erb and write the following in hello.js.erb :为了能够做到这一点,您需要为每个主机创建一个部分 - 类似于_host.html.erb并在hello.js.erb编写以下hello.js.erb

$('#show_hosts').html(<%= render partial: 'host', collection: @hosts %>)

Where @hosts is the name I assume you're using for the collection of hosts to be shown in show_hosts.html.erb , though I must admit I'm a bit confused because you use @test_queues in your controller.其中@hosts是我假设您用于在show_hosts.html.erb显示的主机集合的show_hosts.html.erb ,但我必须承认我有点困惑,因为您在控制器中使用@test_queues

For what it's worth (if I remember correctly) you also need to add format.js to your controller in order to render the hello.js.erb template.对于它的价值(如果我没记错的话),您还需要将format.js添加到您的控制器以呈现hello.js.erb模板。

In your controller add new action named hello在您的控制器中添加名为 hello 的新操作

def hello
 queue = KashmirQueue.find(params[:id]) 
 @test_queues = testQueue.where(:host => queue.host) 
end

move your show.html.erb to a partial like _show.html.erb将你的 show.html.erb 移动到像 _show.html.erb 这样的部分

then in hello.js.erb write然后在 hello.js.erb 中写入

$("#show_hosts").html('#{escape_javascript(render "show.html.erb")}');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM