![](/img/trans.png)
[英]How do you send JSON data in a rails-ujs Rails.ajax POST call (not using jQuery)?
[英]How do you use gmaps4rails to send a an ajax call using UJS in Ruby on Rails?
我按照兩個位置的示例進行了操作:
但他們都不行。 我也沒有得到任何回報。 我目前在RoR 3.2.8中使用1.5.5版本的gmaps4rails。
show_map.js.erb
$('#map_container').show();
$('#map_container').html('<%= escape_javascript( gmaps({:last_map => false}) ) %>');
Gmaps.map = new Gmaps4RailsGoogle();
Gmaps.load_map = function() {
Gmaps.map.map_options.maxZoom = 15;
Gmaps.map.initialize();
Gmaps.map.create_markers();
Gmaps.map.adjustMapToBounds();
Gmaps.map.markers = <%= @json %>;
Gmaps.map.callback();
};
Gmaps.loadMaps();
users_controller.rb
def show_map
@user = User.first
@json = @user.to_gmaps4rails
respond_to do |format|
format.js {}
end
end
show.html.haml
= link_to "Map", show_map_path, :remote => true
#map_container{:style => 'display:none;'}
謝謝你的幫助!
我和@persistence
有同樣的問題,我更喜歡在這個帖子中報告。 我試圖先跟隨wiki示例然后堅持@apneadiving
評論並遵循你的要點,但我仍然遺漏了一些要點。 我將此代碼放在我的控制器中:
events_controller
def index
@json = Event.all.to_gmaps4rails do |event, marker|
marker.title event.title
marker.infowindow event.description
marker.sidebar 'This is a side bar'
end
p @json
respond_with @json
end
在我看來,我粘貼了要點的確切代碼。 當我按下加載按鈕時,我在控制台中檢查我的json信息是否正常,但是由於Javascript錯誤導致地圖未加載:
TypeError: Gmaps.map is undefined
我想我錯過了地圖的某種Javascript初始化?
更新時間05/11/2012:
這確實是問題所在。 結合gist和wiki示例中的javascript,我通過在視圖中放入以下代碼來完成這項工作:
index_view
<!-- create html + load js files but don't create map itself: will be done after ajax call -->
<%= gmaps({:last_map => false}) %>
<br/>
<!-- button to trigger ajax call -->
<button type="button" id="ajax">Load Map</button>
<script type="text/javascript" charset="utf-8">
$(function() {
//hide the empty container
$(".map_container").hide();
// Map initialization
Gmaps.map = new Gmaps4RailsGoogle();
Gmaps.load_map = function() {
Gmaps.map.map_options.maxZoom = 15;
Gmaps.map.initialize();
Gmaps.map.create_markers();
Gmaps.map.adjustMapToBounds();
Gmaps.map.callback();
};
$("#ajax").click(function(){
$.getJSON('/events', function(json){
$(".map_container").show();
Gmaps.loadMaps();
Gmaps.map.addMarkers(json);
})
})
});
</script>
我還留下了一些在GitHub中加載Gmaps4Rails映射的簡單示例: https : //github.com/daviddefco/Gmaps4RailsSamples.git
我是一個RoR和Javascript新手,所以歡迎評論或代碼改進。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.