简体   繁体   English

在rails中,我正在发送一个var以查看,但是在js文件中为nil

[英]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.

相关问题 我是webpack 3的新手,我想与其他js文件共享var,如何? - i'm new to webpack 3 i want to share my var to other js file how to? 出于某种原因,我不能声明一个 var JS - For some reason I'm cant declare a var JS 如何将 js var 传递给 django 视图 - How do I pass a js var to a django view 购物车的 id 在控制器中显示为空,但我确定我正在发送它 NODE JS - the id of cart shows null in controller but i m sure i m sending it NODE JS 如何将smarty变量传递到.js文件以进行var定义? - How can I pass smarty variable to .js file for var definition? 我正在发送Ajax请求,但是我的.php文件没有响应? - I'm sending an Ajax request but I'm getting no response from my .php file? 如果删除了相应的rails视图模板,是否可以删除js文件? - Can I delete a js file if the corresponding rails view template has been deleted? Rails 4 Ajax NoMethodError-我的create.js.erb文件中nil:NilClass:的未定义方法&#39;id&#39; - Rails 4 Ajax NoMethodError - undefined method `id' for nil:NilClass: in my create.js.erb file 为什么我得到的var undefined - Why I'm getting the var undefined Rails:我在使用JavaScript和Rails时遇到问题。 如何使typist.js正常工作? - Rails: I'm having issues with javascript and rails. How do I get typist.js to work?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM