Rails:将数据传递给javascript

我是Rails的新手,我在控制器中有:

class PagesController < ApplicationController def home @temp = "Hello" end end 

我已经读过,我必须将javascript代码放在application.js中(告诉我,如果是),我有:

 window.onload=function(){alert("")} 

显然警告打印字符串“”如何将变量@temp传递给javascript,以便警报可以打印Hello?

谢谢

我写了一篇关于如何将Ruby对象传递给客户端的文章 。 Ryan Bates 在将数据传递给JS方面也有出色的RailsCast 。

在视图中添加一个div,它对应于您加载页面时不可见的PagesControlle #home操作,但将包含存储在Ruby对象中的数据:

 # views/pages_controllers/home.html.erb <%= content_tag :div, class: "temp_information", data: {temp: @temp} do %> <% end %> 

加载包含此div的页面并查看页面源。 您可以看到存储在.temp_information div中的Ruby对象。 打开JavaScript控制台以将JavaScript对象作为JavaScript对象访问:

 $('.temp_information').data('temp') 

您不需要将JS添加到JS部分,也可以使用资产管道。

我做了类似的事情,但比gon简单。 我的ApplicationController有以下内容。

 def javascript_variables(variables) @javascript_variables ||= {} @javascript_variables.merge!(variables) end 

在控制器动作中,我可以做类似的事情

 def some_action javascript_variables(user: current_user) end 

在我的ApplicationHelper我有类似的东西

 def javascript_variables(variables = nil) @javascript_variables ||= {} @javascript_variables.merge!(variables) and return if !variables.nil? output = '' padding = @javascript_variables.keys.group_by(&:size).max.first @javascript_variables.each do |variable, value| output << "#{variable.to_s.ljust(padding)} = #{value.to_json},\n " end raw "var " + output.strip.html_safe.gsub(/\,\Z/m, ';') end 

最后在我的布局中我有

  

这给了我这样的东西(从我的应用程序中的一个真实的例子)

  

看看这个。

http://tech.thereq.com/post/17243732577/rails-3-using-link-to-remote-true-with-jquery-ujs

最简单的方法之一是使用js.erb文件,您可以在其中执行ruby标记来访问您在控制器操作中定义的变量。

您需要在控制器操作中使用respond_to块,指定能够响应javascript的操作。

items_controller.rb

 class ItemsController < ApplicationController def action respond_to do |format| format.js #format.html {} # These are for allowing other types of formats to be responded to. #format.json {} # But they are not necessary for using this js.erb way of doing things. end end end 

/views/items/action.js.erb

 $(div).html('The cat has erased your page');