Ruby-on-rails Rails:将数据传递给 javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18162197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails: pass data to javascript
提问by Tom
i'm new in Rails and in a controller i have:
我是 Rails 的新手,在控制器中我有:
class PagesController < ApplicationController
def home
@temp = "Hello"
end
end
I have read that i must put the javascript code in application.js (tell me if true) and i have:
我已经读到我必须将 javascript 代码放在 application.js 中(如果是真的告诉我),我有:
window.onload=function(){alert("<%= j @temp %>")}
Obviously that alert print the string "<%= j @temp %>" How can i pass the variable @temp to the javascript so that the alert can print Hello?
显然,警报打印字符串“<%= j @temp %>” 如何将变量@temp 传递给javascript,以便警报可以打印Hello?
Thanks
谢谢
回答by Powers
I wrote an article on how to pass Ruby objects to the client. Ryan Bates also has an excellent RailsCast on passing data to JS.
我写了一篇关于如何将 Ruby 对象传递给客户端的文章。Ryan Bates在向 JS 传递数据方面也有出色的RailsCast。
Add a div to your view that corresponds to your the PagesControlle#home action that will not be visible when you load the page but will contain the data stored in the Ruby objects:
将一个 div 添加到您的视图中,该 div 对应于您的 PagesControlle#home 操作,该操作在您加载页面时将不可见,但将包含存储在 Ruby 对象中的数据:
# views/pages_controllers/home.html.erb
<%= content_tag :div, class: "temp_information", data: {temp: @temp} do %>
<% end %>
Load the page with this div included and view the page source. You can see your Ruby objects stored in the .temp_informationdiv. Open up the JavaScript console to access the Ruby objects as JavaScript objects:
加载包含此 div 的页面并查看页面源代码。您可以看到存储在.temp_informationdiv中的 Ruby 对象。打开 JavaScript 控制台以将 Ruby 对象作为 JavaScript 对象访问:
$('.temp_information').data('temp')
You do not need to add your JS to a JS partial, you can also use the asset pipeline.
您不需要将您的 JS 添加到 JS 部分,您也可以使用资产管道。
回答by deefour
I do something similar to, but simpler than gon. I have the following in my ApplicationController.
我做了类似的事情,但比gon更简单。我的ApplicationController.
def javascript_variables(variables)
@javascript_variables ||= {}
@javascript_variables.merge!(variables)
end
Within a controller action I can then do something like
在控制器动作中,我可以做类似的事情
def some_action
javascript_variables(user: current_user)
end
In my ApplicationHelperI have something like this
在我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
and finally in my layout's <head>I have
最后在我的布局中<head>我有
<script>
<%= javascript_variables %>
</script>
This gives me something like this (from a real example in my application)
这给了我这样的东西(来自我应用程序中的一个真实示例)
<script>
var pageModule = "site/index",
isCustomer = false,
utype = "normal",
isAnonymous = true,
keyboardShortcuts = false,
pubnub = null,
requestToken = "3zj974w074ftria3j";
</script>
回答by ahnbizcad
Take a look at this.
看看这个。
http://tech.thereq.com/post/17243732577/rails-3-using-link-to-remote-true-with-jquery-ujs
http://tech.thereq.com/post/17243732577/rails-3-using-link-to-remote-true-with-jquery-ujs
One of the easiest ways is to use js.erb file, where you can do ruby tags to access variables that you defined in the controller action.
最简单的方法之一是使用 js.erb 文件,您可以在其中使用 ruby 标记来访问您在控制器操作中定义的变量。
You need to use a respond_to block in the controller action, specifying the action to be able to respond to javascript.
您需要在控制器操作中使用 respond_to 块,指定能够响应 javascript 的操作。
items_controller.rb
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
/views/items/action.js.erb
$(div).html('The cat has erased your page');

