首页 > 解决方案 > "Uncaught SyntaxError: Unexpected token <" when trying to use content of Rails array in Javascript

问题描述

In Rails 5 I want to use the content of a Rails array inside Javascript:

in my harddisk_controller.rb:

@locations = Harddisk.select(:location).distinct # grab a collection of distinct harddisk locations objects
@harddisk_locations = []
@locations.each do |location|
  @harddisk_locations << location.location # put only the location names into an array
end

I'm trying to achieve to load the content of Rails' @harddisk_locations into Javascript's harddisk_locations:

in application.js:

var harddisk_locations = [<%= raw @harddisk_locations.to_json %>];

But I'm getting the error message with highlight on [<%= raw @harddisk_locations.to_json %>] in my browser console:

Uncaught SyntaxError: Unexpected token <

I assume Javascript is complaining about the

<

right after

[

character. How to fix this?

标签: javascriptruby-on-rails

解决方案


问题是您对js. 这就是为什么您需要重命名application.jsapplication.js.erb.

请注意,如果要将字符串注入 erb,则需要使用引号:

var harddisk_locations = ["<%= somestring %>"];

在你的情况下,我猜,raw @harddisk_locations.to_json是一个有效的 json,所以不需要引号。


推荐阅读