24

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

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

我已经读到我必须将 javascript 代码放在 application.js 中(告诉我是否属实)并且我有:

window.onload=function(){alert("<%= j @temp %>")}

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

谢谢

4

3 回答 3

65

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

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

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

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

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

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

于 2013-08-10T13:25:48.353 回答
5

我做了类似的事情,但比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

最后在我的布局<head>

<script>
  <%= javascript_variables %>
</script>

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

<script>
  var pageModule        = "site/index",
      isCustomer        = false,
      utype             = "normal",
      isAnonymous       = true,
      keyboardShortcuts = false,
      pubnub            = null,
      requestToken      = "3zj974w074ftria3j";
</script>
于 2013-08-10T13:44:48.450 回答
0

看看这个。

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');
于 2014-07-17T08:30:55.247 回答