Rails .js.erb文件中的Ruby数组到js数组 [英] Ruby array to js array in .js.erb file on rails
问题描述
我正在尝试将ruby数组转换为js.erb文件中的js数组.我已经在堆栈溢出中检查了所有与此有关的问题,但它对我不起作用.
I'm trying to turn a ruby array into a js array in a js.erb file. I've checked all questions on this in stack overflow but it isn't working for me.
这是功能
function c(c) {
js_array = <%= raw @keys.to_json %>;
b.selection.remove(), b.html.insert('js_array[0]');
}
它引发错误未捕获的TypeError:无法读取null的属性"0"
我还在学习js,所以我不确定这里出了什么问题
Im still learning js so im not sure what is going wrong here
ruby @keys数组中绝对有数据,因为我正在同一页上打印数据.
The ruby @keys array defiantly has data in it because I'm printing that on the same page.
如果我将数组更改为 js_array = ['gwfe','efw','efwe'];
,它就可以正常工作.这使我相信在尝试将ruby数组转换为js数组时出了问题.
And if i change the array to js_array = ['gwfe', 'efw', 'efwe'];
it works fine. This makes me believe something is going wrong when trying to convert the ruby array into a js array.
推荐答案
我假设您正在从db或local获取@keys数据.您能否尝试 gon gem 将值从ruby传递给js.这是相同的Railscast教程: http://railscasts.com/episodes/324-passing-data-to-javascript?view = asciicast
I assume, you are gettings @keys data from db or local. Could you try gon gem to pass the values from ruby to js. Here is the railscast tutorial for the same: http://railscasts.com/episodes/324-passing-data-to-javascript?view=asciicast
看看,是否行得通.
让我知道.
这篇关于Rails .js.erb文件中的Ruby数组到js数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!