简体   繁体   中英

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.

Suppose I pass a variable @note that has attributes location, content, and tags (associated tags). How to I access these attributes in the jQuery file? 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. 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.

In your case it can be solved quite easily:

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

# JS
var content = gon.note.content;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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