3

Given a controller MapsController:

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

This renders the JSON just fine. But now, I'd like to pass along some HTML to inject into the 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);
});

This JavaScript assumes a .listing and .infowindow attribute in each returned JSON-Object. They should contain HTML, rendered with the partials campings/_infowindow.html.haml and campings/_listing.html.haml.

Is this the correct angle to tackle this? Or should I rather build the HTML within the JavaScript and avoid sending HTML? If so, is there still a way to use partials to build the actual HTML?

How can I add listing and infowindow to the ObjectsCamping model does not have these fields?

4

2 回答 2

1

也许有点粗糙(而不是 100% 超级“Rails 方式”)但在类似情况下对我来说工作正常:

render :text => {:result => "success",
                 :document_row => render_to_string(
                                  :file => "admin/documents/_document_row",
                                  :formats => "html",
                                  :layout => false,
                                  :locals => {:documentable => documentable})}.to_json

所以大致只是生成一个哈希并使用 render_to_string 从 _document_row 模板中获取 html。

于 2013-04-24T14:28:42.943 回答
0

如果您使用类似 KnockoutJS 或其他 javascript 数据绑定或模板工具,您可以在页面中有一个骨架“模板”,当您发出 ajax 请求时,它会填充露营列表。

它的工作方式是您将您的表格或列表或任何露营列表绑定到您的 Knockout 模型中的露营对象数组。当您发出 ajax 请求时,您只需使用返回的 json 更新该数组。当该数组更新时,DOM 会自动更新以显示新列表。这使您的 ajax 请求仅获取数据而不是所有 HTML 标记,这意味着通过网络传输的字节数更少,并且您可以将获取新数据的行为与基于该​​数据更新 DOM 的行为分开。

于 2013-04-24T14:28:44.467 回答