简体   繁体   中英

How can I pass rails data to javascript?

I have a Rails 4 application. I want to display locations on google maps street view. Longitude and latitude are saved in database, so it can only accessed through rails. Controller :

@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);
}

As you can notice, when using addMarker function I should provide latlng value which is rendred by rails controller. How can I pass values from rails to Javascript?

     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>

Hope this will help you :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM