简体   繁体   English

如何使用gon访问变量属性(在jQuery和Rails中)

[英]how do I access variable attributes using gon (in jQuery & Rails)

I was recently pointed to gon for passing variables from my controller to javascripts available on a page. 我最近指出gon将变量从我的控制器传递到页面上可用的javascripts。

Suppose I pass a variable @note that has attributes location, content, and tags (associated tags). 假设我传递了一个变量@note,它具有属性location,content和tags(关联标签)。 How to I access these attributes in the jQuery file? 如何在jQuery文件中访问这些属性? if I do: 如果我做:

 alert(gon.note)

I get an alert [object][Object] 我收到警报[对象] [对象]

I want to access the content to output a string ie 我想访问内容以输出字符串即

 var string = gon.note.content

gon.note.content doesn't work. gon.note.content不起作用。 Any pointers? 有什么指针吗?

I suppose your @note is an AR instance, then for sure it can't be passed in JS directly, because only simple data types like strings, array, hashes and so on can be exchanged between Ruby and Javascript. 我想你的@note是一个AR实例,然后肯定它不能直接在JS中传递,因为只有简单的数据类型如字符串,数组,哈希等可以在Ruby和Javascript之间交换。

In your case it can be solved quite easily: 在您的情况下,它可以很容易地解决:

# controller
gon.note = @note.attributes # returns a hash

# JS
var content = gon.note.content;

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

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