Ruby array to js array in .js.erb file on rails

[亡魂溺海] 提交于 2021-01-28 18:14:09

问题


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.

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

Im still learning js so im not sure what is going wrong here

The ruby @keys array defiantly has data in it because I'm printing that on the same page.

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.


回答1:


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

And see, if that works.

Let me know.



来源:https://stackoverflow.com/questions/34845582/ruby-array-to-js-array-in-js-erb-file-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!