javascript - "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?
解决方案
问题是您对js
. 这就是为什么您需要重命名application.js
为application.js.erb
.
请注意,如果要将字符串注入 erb,则需要使用引号:
var harddisk_locations = ["<%= somestring %>"];
在你的情况下,我猜,raw @harddisk_locations.to_json
是一个有效的 json,所以不需要引号。
推荐阅读
- mysql - 在 Golang 网站中使用模板显示 mysql 表
- python - 尝试将颜色渐变添加到 Matplotlib 图表
- angular - 什么可能导致在 AOT 构建中而不是在开发环境中发生的带有对象原型的 Uncaught TypeError?
- r - 使用局部变量更新函数
- android - Android使用相机意图并在本地保存图像
- java - 为 Android (Java) 实施 Google 保存的游戏
- java - 读取unicode字符代码JAVA
- python - Url 以 UTF-8 编码,但 Python 试图将其读取为 cp1256
- numpy - Xtensor:分配给视图时需要帮助
- java - 让子类序列化为超类的实例?