Rails:将数据传递给javascript [英] Rails: pass data to javascript

查看:97
本文介绍了Rails:将数据传递给javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i'm new in Rails and in a controller i have:

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

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

I have read that i must put the javascript code in application.js (tell me if true) and i have:

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

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

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?

谢谢

推荐答案

我写了一篇关于如何将Ruby对象传递给客户端。 Ryan Bates还有一个很好的 RailsCast将数据传递给JS

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.

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

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:

# 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对象访问:

Load the page with this div included and view the page source. You can see your Ruby objects stored in the .temp_information div. Open up the JavaScript console to access the Ruby objects as JavaScript objects:

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

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

You do not need to add your JS to a JS partial, you can also use the asset pipeline.

这篇关于Rails:将数据传递给javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆