[英]How to access an instance variable inside a Javascript function in Ruby on Rails application?
I have a form for editing profiles.我有一个用于编辑配置文件的表单。 Rails automatically generates the form id as 'edit_profile_##' where ## is the profile id of the current user(instance variable-@profile_id). Rails 自动生成表单 ID 为“edit_profile_##”,其中 ## 是当前用户的配置文件 ID(实例变量-@profile_id)。 I need to use this form id for my javascript functions.我需要将此表单 ID 用于我的 javascript 函数。 Is there a way to get the current user's profile id inside js?有没有办法在js中获取当前用户的个人资料ID? Or is there a way I can override the automatic id generation by rails?或者有什么方法可以覆盖 Rails 的自动 id 生成?
you have to send that using function parameter你必须使用函数参数发送它
.html.erb .html.erb
<script type="text/javascript">
var user_id = <%= @profile_id %>; // for integer
var user_name = '<%= @profile_name %>'; // for string
abc(user_id)// this is your function in .js file
</script>
.js .js
function abc(id){
alert(""+id)
}
Are you using normal *.html.erb views?您使用的是普通的 *.html.erb 视图吗?
Can't you do something like :你不能做这样的事情:
<script type="text/javascript">
user_id = <%= @profile_id %>;
</script>
? ?
lets say you have @user = {'name'=>'steve'}
in the controller假设您在@user = {'name'=>'steve'}
有@user = {'name'=>'steve'}
now your html page can render <p> <%=@user['name']%> </p>
现在你的 html 页面可以呈现<p> <%=@user['name']%> </p>
now lets say you want to be able to access @user in your .js file;现在假设您希望能够在 .js 文件中访问 @user; add thisThing & data-url to your tag <p id="thisThing" data-url="<%=@user%>" > <%=@user['name']%> </p>
将 thisThing 和 data-url 添加到您的标签<p id="thisThing" data-url="<%=@user%>" > <%=@user['name']%> </p>
in your .js file var userInfo = $('#thisThing').data('url')
在你的 .js 文件中var userInfo = $('#thisThing').data('url')
now you got userInfo in your .js (its in string)现在你在你的 .js 中得到了 userInfo(它是字符串)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.