简体   繁体   English

Rails .js.erb文件中的Ruby数组到js数组

[英]Ruby array to js array in .js.erb file on rails

I'm trying to turn a ruby array into a js array in a js.erb file. 我正在尝试将ruby数组转换为js.erb文件中的js数组。 I've checked all questions on this in stack overflow but it isn't working for me. 我已经检查了所有关于堆栈溢出的问题,但是它对我不起作用。

Here is the function 这是功能

  function c(c) {
   js_array = <%= raw @keys.to_json %>;
   b.selection.remove(), b.html.insert('js_array[0]');
    }

It throws the error Uncaught TypeError: Cannot read property '0' of null 它引发错误Uncaught TypeError: Cannot read property '0' of null

Im still learning js so im not sure what is going wrong here 我还在学习js,所以我不确定这里出了什么问题

The ruby @keys array defiantly has data in it because I'm printing that on the same page. ruby @keys数组中绝对有数据,因为我正在同一页上打印数据。

And if i change the array to js_array = ['gwfe', 'efw', 'efwe']; 如果我将数组更改为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. 这使我相信在尝试将ruby数组转换为js数组时出了问题。

I assume, you are gettings @keys data from db or local. 我想,你是从数据库或本地获取@keys数据。 Could you try gon gem to pass the values from ruby to js. 您可以尝试使用gon gem将值从ruby传递给js。 Here is the railscast tutorial for the same: http://railscasts.com/episodes/324-passing-data-to-javascript?view=asciicast 这是相同的Railscast教程: http ://railscasts.com/episodes/324-passing-data-to-javascript?view=asciicast

And see, if that works. 看看是否可行。

Let me know. 让我知道。

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

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