如何使用gon访问变量属性(在jQuery& Rails中) [英] how do I access variable attributes using gon (in jQuery & Rails)

查看:116
本文介绍了如何使用gon访问变量属性(在jQuery& Rails中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近被指责gon要将变量从控制器传递到页面上可用的javascript.

I was recently pointed to gon for passing variables from my controller to javascripts available on a page.

假设我传递了一个变量@note,它具有属性位置,内容和标签(关联的标签).如何访问jQuery文件中的这些属性?如果我这样做:

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不起作用.有指针吗?

gon.note.content doesn't work. Any pointers?

推荐答案

我想您的@note是AR实例,那么可以确定它不能直接在JS中传递,因为只有简单的数据类型(例如字符串,数组) ,哈希等可以在Ruby和Javascript之间交换.

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.

您的情况很容易解决:

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

# JS
var content = gon.note.content;

这篇关于如何使用gon访问变量属性(在jQuery& Rails中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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