简体   繁体   English

(rails3)将ruby变量传递到javascript文件

[英](rails3) passing ruby variables to javascript file

When rendering a javascript file (not RJS, just a regular JS file) from a rails controller, is there a way to pass variables to it, which can then be used by functions in the JS file being called? 从Rails控制器呈现javascript文件(不是RJS,只是普通的JS文件)时,是否可以将变量传递给它,然后可以由被调用的JS文件中的函数使用这些变量? I've tried :locals => {} but that doesn't work. 我试过了:locals => {},但是不起作用。

If you're rendering inside a js file you should use rjs. 如果要在js文件中进行渲染,则应使用rjs。 If you really don't like rjs (understandable) then how about rendering your variables first, then including your script? 如果您真的不喜欢rjs(可理解),那么如何首先呈现变量,然后包含脚本呢?

<% javascript_tag do %>
  var my_var = <%= @my_var.to_json %>;
<% end %>
<% javascript_include_tag 'your-js-file-that-expects-my_var-to-exist.js' %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM