如何在js文件中获取rails控制器变量 [英] How to get rails controller variable in js file

查看:223
本文介绍了如何在js文件中获取rails控制器变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在rails控制器中有一个变量,如

I have a variable in rails controller like

def index
@approveflag = true
end

我需要在我的javascript代码中访问此变量,我使用下面给出的代码
in index.html.erb

I need to access this variable in my javascript code, I used the code given below in index.html.erb

<script>
alert("<%=@approveflag%>")
<script>

结果为true时工作正常。但是当我将此代码移动到相应的.js文件时它会发出结果字符串<%= @ approveflag%>的警告。
是什么原因。我该如何解决这个问题?

It works fine with result "true".But when I moved this code to its corresponding .js file it gives an alert with result string ""<%=@approveflag%>"". What is the reason. How can I solve this?

提前致谢。

推荐答案

我个人不喜欢将js与erb混合,所以我会做这样的事情:

I personally don't like mixing js with erb so I would do something like this:

in index.html.erb

in index.html.erb

<%= content_tag :div, '', id: 'mycontainer', data: { source: @approveflag } %>

in js

$('#mycontainer').data('source')
alert($('#mycontainer').data('source'))

如果您拥有该实例变量的值,您可以在link_to中添加数据属性。

And you have the value from that instance variable, you can add a data attribute in a link_to if you want.

这篇关于如何在js文件中获取rails控制器变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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