[英]in rails I'm sending a var to view and but in js file is nil
I'm sending a var in rails to use it in the view, I have a js file name charts.js.erb that is called and I need to use the var in that js file but is nil 我正在rails中发送一个var以在视图中使用它,我有一个js文件名为charts.js.erb,我需要在该js文件中使用var,但它为nil
in my controller a have the method 在我的控制器中有一种方法
def index
@asd = 'hellow'
end
in my view i can do 我认为我可以做到
.div= @asd
but in my javascript file 但是在我的javascript文件中
alert('<%= @asd %>');
@asd var is nil, i've tested using other ruby code an works, but the vars doesn't work @asd var为零,我已经使用其他红宝石代码进行了测试,但是该vars无法正常工作
That's not how ERB works with JavaScript. 这不是ERB与JavaScript一起工作的方式。 The JS files are generated before runtime, so they do not have access to dynamic server values like that.
JS文件是在运行时之前生成的,因此它们无法访问这样的动态服务器值。
The pattern that I usually follow is to place the server-generated value somewhere in the DOM for the JS to pick up. 我通常遵循的模式是将服务器生成的值放在DOM中的某个位置,以供JS使用。
<div id="asd" data-asd="<%= @asd %>">
Then if you're using jQuery, for example: 然后,如果您使用的是jQuery,例如:
var asd = $('#asd').data('asd');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.