鑑於控制器MapsController
:將呈現的HTML,以JSON
class MapsController < ApplicationController
def index
@campings = Camping.finm(:all) #in reality a much more complex scope.
respond_to do |format|
format.html
format.json { render :json => @campings }
end
end
end
這使得JSON就好了。但現在,我想帶一些HTML傳遞給注入到DOM:
$.ajax({
dataType: "json",
url: "maps.json?bounding=45.446465,-4.935988,53.944621,17.036668",
}).done(function (data) {
//...
var gInfoWindow = new google.maps.InfoWindow({
content: camping.infowindow
});
//...
$("#campings").append(camping.listing);
});
這個JavaScript假定.listing
和.infowindow
屬性在返回的每個JSON-對象。它們應該包含使用部分campings/_infowindow.html.haml
和campings/_listing.html.haml
呈現的HTML, 。
這是解決這個問題的正確角度嗎?還是應該在JavaScript中構建HTML並避免發送HTML?如果是這樣,是否還有一種方法可以使用partials來構建實際的HTML?
如何將listing
和infowindow
添加到對象Camping
模型沒有這些字段?
我不知道這是如何呈現一個集合。在我看來,這需要包裹在一些'.each'或'.map'塊中,而不是? – berkes 2013-04-24 14:47:47
對於你可以使用的集合:集合而不是:locals(假設你的模板是用這種方式編碼的)。但是,是的,你可以先創建一個字符串,並從render_to_string中「收集」幾個結果。 – 2013-04-24 14:51:15
我接受了這個答案,因爲它解釋了「render_to_string」,後者證明是解決我的問題的關鍵。 – berkes 2013-05-01 10:07:17