从 Ajax 调用时不呈现布局 [英] Don't render layout when calling from Ajax
问题描述
我有一个名为 index 的 rails 操作,用于呈现我页面的内容和布局.当我使用浏览器转到/index 操作时,它会按预期工作.我还希望能够通过使用 Ajax 调用它来呈现此操作,我正在使用以下方法执行此操作:
I have a rails action called index that renders the content for my page along with the layout. When I go to the /index action with a browser it works like expected. I want to be able to also render this action by calling it with Ajax, I am doing this using the following:
<%= link_to "Back", orders_path, :id => 'back_btn', :remote => true %>
<%= javascript_tag do %>
jQuery("#back_btn").bind("ajax:complete", function(et, e){
jQuery("#mybox").html(e.responseText);
});
<% end %>
当以这种方式调用动作时,我希望它呈现并将索引动作传回,不包括布局.我该怎么做?
When the action is called this way I would like it to render and pass the index action back, excluding the layout. How can I do this?
推荐答案
您应该能够像这样将 format.js 操作添加到您的控制器操作中:
You should be able to add a format.js action to your controller action like so:
respond_to do |format|
format.js
format.html
format.json { render json: @foos }
理想情况下,您需要创建一个 index.js.erb 文件来构建页面内容:
Ideally, you would want to create a index.js.erb file that would build the contents of the page:
$('#foos_list').update("<%= escape_javascript(render(@foos)) %>");
如果您要更新 div 的内容,基本上是更新布局内的整个页面,那么您将需要对其进行一些更改.在 format.js 中,您可以这样做:
If you're going to update the contents of a div, to basically update a whole page inside of a layout, then you're going to want to change it up a little bit. Inside of the format.js, you can do this:
format.js { render 'foos/index', :layout => false }
但是如果你想使用ajaxified前端,我可以推荐一个框架来做这个,比如Spine?它对帮助您构建网站大有帮助.
But if you're trying to go with an ajaxified front-end, may I recommend a framework for doing this, like Spine? It will go a long way in helping you build your site.
此外,使用这样的框架将迫使您按照@Zepplock 的第二个建议分离您的应用程序.
Also, using a framework like this will force you to separate your application per @Zepplock's second suggestion.
这篇关于从 Ajax 调用时不呈现布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!