如何在 Javascript 代码中访问 rails 变量? [英] How to access rails variables within Javascript code?

查看:31
本文介绍了如何在 Javascript 代码中访问 rails 变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Rails 3.0.5

I am using Rails 3.0.5

我有一个使用 jQuery 下拉清单 并且我希望在我的物品控制器的编辑"操作中使用我的表单时,复选框显示哪些项目已被选中,哪些尚未选中.

I have a javascript code that uses jQuery dropdown checklist and I would like to have the checkboxes displaying which item is checked already and which is not, when using my form in the 'Edit' action of my belongings controller.

基本上,它可以在 Javascript 中这样工作:

Basically, it can work like this in Javascript:

$('element').val([1,3,4]);
$('element').dropdownchecklist();

让我们说在我的控制器编辑操作中,我有一个名为 @selected_items 的实例变量,它包含被选择的项目(这里:@selected_items = [1,3,4]),我想使用将此实例变量的值添加到我的 Javascript 代码中,我该如何继续?如何在 .js 文件中访问此实例变量的值?

Let us say that in my controller, edit action, I have a instance variable called @selected_items that contains the items that are selected (here: @selected_items = [1,3,4]) and I would like to use the value of this instance variables into my Javascript code, how could I proceed ? How could I access the value of this instance variable in a .js file ?

非常感谢您的回答!

推荐答案

只需在视图中编写 javascript,并在适当的位置将 @selected_items 数组打印为 json:

Just write the javascript in your view, and at the appropriate place, print the @selected_items array as json:

app/views/*/*.html.erb

<script>
  $('element').val(<%= @selected_items.to_json %>);
  $('element').dropdownchecklist();
</script>

如果 to_json 无法序列化更复杂的对象,您也可以使用 Gon gem.

You can also use the Gon gem if to_json cannot serialize more complicated objects.

这篇关于如何在 Javascript 代码中访问 rails 变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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