【问题标题】:How can I pass rails data to javascript?如何将rails数据传递给javascript?
【发布时间】:2016-04-12 13:22:02
【问题描述】:

我有一个 Rails 4 应用程序。我想在谷歌地图街景上显示位置。经度和纬度保存在数据库中,因此只能通过rails访问。 控制器:

@posts.each do |post|
  markers << post.marker_single_show
end

Javascript:

function addMarker(latLng, map, icon) {
  if (formMarker !== undefined) {
    formMarker.setMap(null);
  }
  formMarker = new google.maps.Marker({
    position: latLng,
    animation: google.maps.Animation.BOUNCE,
    title: "localisation",
    icon: icon
  });
  formMarker.setMap(map);
  var latlngbounds = new google.maps.LatLngBounds();
  latlngbounds.extend(latLng);
  map.fitBounds(latlngbounds);
  map.panToBounds(latlngbounds);
}

如您所见,在使用 addMarker 函数时,我应该提供由 rails 控制器渲染的 latlng 值。 如何将值从 rails 传递到 Javascript?

【问题讨论】:

  • 提供代码示例会更有帮助。根据前端的设置方式,您可能可以在控制器中传递一个实例变量设置,然后通过类似 onclick 函数的方式将其传递给谷歌地图 API。我知道那里还有一些宝石可以帮助将数据传递给 JS(对您的问题进行类似的谷歌搜索)。此外,还有一些方法可以在控制器中传回 json。

标签: javascript google-maps ruby-on-rails-4.2


【解决方案1】:
     app/controllers/some_controller.rb
     def someMethod
      @railsVariable = Model.all or Model.find(id)
      end
     in its view you can do something like this

<script>
  var JavascriptVariable = <%= @railsVariable %>;
</script>

希望对你有帮助:)

【讨论】:

  • 对于那些有同样问题的人,我使用了@ashwintastic 建议的hack,效果很好。
猜你喜欢
  • 2021-05-24
  • 2013-02-08
  • 2013-08-12
  • 2015-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多