簡體   English   中英

Ruby on Rails如何將數據從控制器傳遞到html中的javascript

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

我在鐵軌上的紅寶石上做谷歌地圖。 我正在嘗試在地圖上實現動態標記文本。

我找到了一種在java腳本中添加標記文本的方法。 如何將我的控制器數據(從數據庫中檢索的字符串數據)傳遞給java?我搜索了其他帖子,但無法理解他們的答案。

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>

我想將這個“text”替換為一個名為text的變量,它從我的控制器復制@somestring,比如說gmaps_controller.rb

我試過添加文本:“<%= @somestring%>”我把它放在var homelatlng下,但沒有工作。

我也試過了

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

我把它放在一個單獨的javascript標簽之后

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

也不行。

有沒有其他方法可以將數據傳遞給控制器​​?請詳細告訴我我是一個新手。 提前致謝

如何在html中將數據從控制器傳遞到javascript

您無法訪問資產中的ruby變量 你最好的選擇是使用html5 data attributes 從你的控制器傳遞數據,或者我應該說查看到javascript。 讓我們假設您有這樣的html元素:

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

然后在javascript中像這樣訪問它

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

使用gon gem。

第1步:在gemfile中添加gem'gon'

第2步:運行bundle install

第3步:在視圖的標頭標記中添加<%= include_gon%>

第4步:在控制器中添加gon.yourpassdata =“sometext”

第5步:從您的視圖中獲取數據,說出提醒(gon.yourpassdata)

完成了!

更清晰的方式來顯示地圖+動態標記在地圖+動態infowindow +可點擊的infowindows ...。傳遞所需的對象,並包括從谷歌地圖js的地方...這個代碼已准備好工作。我動態添加標記到使用$.each地圖並將其推入數組

我在這里提出了類似的問題

在你的控制器......

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

在此js.erb(更新視圖與動態標記記住你有這樣的選擇(任何其它也)你cliked在頁面上新地圖),在這里我有一個空的地圖,與動態標記填充 地圖替換它

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

_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM