gpt4 book ai didi

javascript - "Uncaught SyntaxError: Unexpected token <"尝试在 Javascript 中使用 Rails 数组的内容

转载 作者:行者123 更新时间:2023-11-30 08:21:55 27 4
gpt4 key购买 nike

在 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 %>];

但我在浏览器控制台中收到错误消息,其中突出显示 [<%= raw @harddisk_locations.to_json %>]:

Uncaught SyntaxError: Unexpected token <

我假设 Javascript 正在提示

<

紧接着

[

性格。如何解决这个问题?

最佳答案

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

请注意,如果您想将字符串注入(inject)到 erb 中,您需要使用引号:

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

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

关于javascript - "Uncaught SyntaxError: Unexpected token <"尝试在 Javascript 中使用 Rails 数组的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52148840/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com