我有一个@coords
变量:
#maps controller
def index
@coords = Map.all
end
在index.html.erb中,我有:
<%= content_tag 'div', id: 'coords', data: @coords.to_json do %>
<% end %>
渲染 HTML 页面后我的 content_tag 的样子:
[{"id":1,"vibration_level":456,"lat":"71.45543","lon":"53.43424","time_sent":"1994-05-20T00:00:00.000Z","created_at":"2015-06-13T06:53:30.789Z","updated_at":"2015-06-13T06:53:30.789Z"} ]
如何从 JavaScript 文件访问它。
最佳答案
您应该考虑使用gon gem 。这个 gem 用于将数据从 Rails 发送到 JavaScript。
你可以这样做:
#map controller
def index
@coords = Map.all
gon.coords = @coords.to_json
end
然后你可以在 JS 中访问你的变量:
gon.coords
关于javascript - 如何在 JavaScript 中访问从 Rails 4 Controller 发送的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30818361/