【问题标题】:"Uncaught SyntaxError: Unexpected token <" when trying to use content of Rails array in Javascript尝试在 Javascript 中使用 Rails 数组的内容时出现“Uncaught SyntaxError: Unexpected token <”
【发布时间】:2018-09-03 11:25:31
【问题描述】:

在 Rails 5 中,我想在 Javascript 中使用 Rails 数组的内容:

在我的 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

我正在尝试实现将 Rails 的 @harddisk_locations 的内容加载到 Javascript 的 harddisk_locations 中:

在 application.js 中:

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

但是我在浏览器控制台的 [] 上收到错误消息:

Uncaught SyntaxError: Unexpected token

我认为 Javascript 是在抱怨

紧接着

[

字符。如何解决这个问题?

【问题讨论】:

  • 查看源代码并查看var harddisk_locations = [&lt;%= raw @harddisk_locations.to_json %&gt;]; 呈现的内容

标签: javascript ruby-on-rails


【解决方案1】:

问题是您对js 使用了无效的语法。这就是为什么您需要将 application.js 重命名为 application.js.erb

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

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

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

【讨论】:

  • 如果raw @harddisk_locations.to_json 包含一个有效的 json 格式的字符串,那么该语句不是无效的
  • 只是想知道将harddisk_locations 定义为数组是必要的吗?我的意思是@harddisk_locations 已经是一个数组了。
  • 严格来说@harddisk_locations 是一个哈希,除了位置之外还有很多其他属性。
【解决方案2】:

您在 .js 文件中使用 ERB 语法。更好的解决方案是创建一个新的 .js.erb 文件并在该文件中添加您所需的代码。

关于您的代码的建议,您可以将现有代码替换为@harddisk_locations = Harddisk.select(:location).distinct.map(&amp;:location)

【讨论】:

  • 更简单:@harddisk_locations = Harddisk.pluck(:location).uniq
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-30
  • 1970-01-01
  • 2019-02-08
相关资源
最近更新 更多