Rails:将数据传递给javascript

Rails: pass data to javascript

本文关键字:javascript 数据 Rails      更新时间:2023-09-26

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

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

我读到我必须把javascript代码放在application.js中(如果是真的,请告诉我),我有:

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

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

感谢

我写了一篇关于如何将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的页面并查看页面源代码。您可以看到您的Ruby对象存储在.temp_information分区中。打开JavaScript控制台以访问Ruby对象作为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

最后,在我的布局的<head>中,我有

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

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

<script>
  var pageModule        = "site/index",
      isCustomer        = false,
      utype             = "normal",
      isAnonymous       = true,
      keyboardShortcuts = false,
      pubnub            = null,
      requestToken      = "3zj974w074ftria3j";
</script>

看看这个。

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

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

您需要在控制器操作中使用respons_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');