简体   繁体   English

Ruby on Rails如何将数据从控制器传递到html中的javascript

[英]Ruby on Rails how to pass data from controller to javascript in html

I'm doing google maps on ruby on rails. 我在铁轨上的红宝石上做谷歌地图。 I'm trying to implement dynamic marker text on the map. 我正在尝试在地图上实现动态标记文本。

I find a way to add marker text in java script. 我找到了一种在java脚本中添加标记文本的方法。 How can I pass my controller data( string data retrieved from database) to java?I've searched other posts but cant understand their answer. 如何将我的控制器数据(从数据库中检索的字符串数据)传递给java?我搜索了其他帖子,但无法理解他们的答案。

The javascript in html is html中的javascript是

 <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3&amp;sensor=false"></script>
 <script type="text/javascript" src="../src/markerwithlabel.js"></script>
 <script type="text/javascript">
 function initMap() {

 var latLng = new google.maps.LatLng(49.47805, -123.84716);
 var homeLatLng = new google.maps.LatLng(49.47805, -123.84716);

 var map = new google.maps.Map(document.getElementById('map_canvas'), {
   zoom: 12,
   center: latLng,
   mapTypeId: google.maps.MapTypeId.ROADMAP
 });

 var marker1 = new MarkerWithLabel({
   position: homeLatLng,
   draggable: true,
   raiseOnDrag: true,
   map: map,
   labelContent: *"text"*,
   labelAnchor: new google.maps.Point(22, 0),
   labelClass: "labels", // the CSS class for the label
   labelStyle: {opacity: 0.75}
 });
 </script>

I want to replace this "text" to a variable called text,which copies @somestring from my controller,say gmaps_controller.rb 我想将这个“text”替换为一个名为text的变量,它从我的控制器复制@somestring,比如说gmaps_controller.rb

I have tried add text: "<%= @somestring %>" I put it just under var homelatlng,but no working. 我试过添加文本:“<%= @somestring%>”我把它放在var homelatlng下,但没有工作。

I also have tried 我也试过了

$(document).ready(function(){
var text='<%=j @somestring%>'
})

I put this in a individual javascript tag after 我把它放在一个单独的javascript标签之后

<script type="text/javascript" src="../src/markerwithlabel.js"></script>

also not working. 也不行。

Is there any otherway to pass data to controller?please tell me in detail Im quite a newbie. 有没有其他方法可以将数据传递给控制器​​?请详细告诉我我是一个新手。 thanks in advance 提前致谢

how to pass data from controller to javascript in html 如何在html中将数据从控制器传递到javascript

You can't access ruby variables in your assets . 您无法访问资产中的ruby变量 Your best bet would be to use html5 data attributes to pass data from your controller or rather i should say view to javascript. 你最好的选择是使用html5 data attributes 从你的控制器传递数据,或者我应该说查看到javascript。 Lets suppose you have html element like this: 让我们假设您有这样的html元素:

= link_to "some text", some_path, id: "some_id", data: {value: @some_value}  #where @some_value is set in your controller

and then access it like this in javascript 然后在javascript中像这样访问它

$(document).ready(function(){
  var text =  $("#some_id").data("value");
  // now text will contain some_value
});

Use gon gem. 使用gon gem。

step 1: add gem'gon' in your gemfile 第1步:在gemfile中添加gem'gon'

step 2: run bundle install 第2步:运行bundle install

step 3: add <%= include_gon %> in your view's header tag 第3步:在视图的标头标记中添加<%= include_gon%>

step 4: add gon.yourpassdata="sometext" in your controller 第4步:在控制器中添加gon.yourpassdata =“sometext”

step 5:get your data from your view,say alert(gon.yourpassdata) 第5步:从您的视图中获取数据,说出提醒(gon.yourpassdata)

done! 完成了!

more clearer way to show map + dynamic marker on map + dynamic infowindow + clickable infowindows... .Just pass the required object and include the places js from google map...this code is ready to work.here i dynamically add markers to the map with infowindows using $.each and push it into the array 更清晰的方式来显示地图+动态标记在地图+动态infowindow +可点击的infowindows ...。传递所需的对象,并包括从谷歌地图js的地方...这个代码已准备好工作。我动态添加标记到使用$.each地图并将其推入数组

i raised the similar question here 我在这里提出了类似的问题

in your controller... 在你的控制器......

def show_nearby_locations_to_guest
@nearbys = Place.near("#{params[:address]}", 5,:order => "distance",:units => :km).paginate(:page => params[:page], :per_page => 10)
end

_show_nearby_locations_to_guest.js.erb _show_nearby_locations_to_guest.js.erb

in this js.erb(to update view with new map with dynamic markers keeping in mind you have this selector(anyother also) on the page you cliked) ,here i have a EMPTY map and replacing it with NEW map FILLED with dynamic markers 在此js.erb(更新视图与动态标记记住你有这样的选择(任何其它也)你cliked在页面上新地图),在这里我有一个空的地图,与动态标记填充 地图替换它

$("#map-canvas").html("<%= escape_javascript(render(:partial => 'show_nearby_locations_to_guest')) %>");

_show_nearby_locations_to_guest.html.erb _show_nearby_locations_to_guest.html.erb

<%= javascript_tag do%>
/////use global variable instead of using data-attribute as my resultset can have 100+ records
window.nearbys= <%=raw @nearbys.to_json %>;
<%end%>


<script type="text/javascript">
var pinColor = "000000";
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
function initialize() {
// Display a map on the page
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
map.setTilt(45);
//emtpy array to add dynamic markers
var markers=[];
//emtpy array to add dynamic infowindows 
var infoWindowContent=[];
$.each(nearbys, function(index) {
markers.push([nearbys[index]['title'], nearbys[index]['latitude'],nearbys[index]['longitude']]);
infoWindowContent.push(['<div class="info_content" >' +
'<h3'+nearbys[index]['title']+'</h3>' +
'<p><i>'+nearbys[index]['about']+'</i></p>' +
'<p><a href="/places/show/'+nearbys[index]['id']+'" data-remote="true" title="view more">view more</a></p>' +
'</div>']);
});
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow({ maxWidth: 320 }), marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld="+markers[i][0].charAt(0).toUpperCase()+"|FE7569|" + pinColor,
new google.maps.Size(21, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0],
icon: pinImage
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});
}//initialize ends
$(document).ready(function(){
$('#map-canvas').html("<p class='text-center text-alert'><b><i>Loading map...</i><i class='fa fa-spinner fa-spin fa-2x'></i></b></p>");
//load the map after 2 seconds so that the same code can work on modals as well
setTimeout('initialize()', 2000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 json 数据从 ruby controller 传递到 javascript(导轨)? - How to pass json data from ruby controller to javascript (Rails 6.1)? Rails:如何将数据从Ruby传递到Javascript - Rails: how to pass data from Ruby to Javascript 在Rails中将数据从Controller传递到Javascript - Pass data from Controller to Javascript in Rails 如何在Ruby on Rails中将更新javascript变量传递给控制器​​? - How to pass updating javascript variable into form to controller in Ruby on Rails? How to use AJAX request to pass user's HTML5 location in a class variable from JavaScript to Rails controller? - How to use AJAX request to pass user's HTML5 location in a class variable from JavaScript to Rails controller? 如何将位置坐标从HTML5和javascript传递到Rails控制器和mongodb模型? - how do i pass location coordinate getting from HTML5 & javascript to my rails controller and mongodb model ? 如何将原始数据从控制器传递到javascript中? - How to pass raw data from controller into javascript? 如何:在Laravel 4中将数据从控制器传递到JavaScript? - How to: pass data from controller to JavaScript in Laravel 4? 如何将JSON数据从控制器传递到JavaScript - How to pass json data from the controller to javascript 如何将数据从 controller 传递到 javascript? - How to pass data from controller to javascript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM