如何通过AJAX Rails中取得HTML请求作出回应 [英] How to respond to HTML requests made via AJAX in Rails
问题描述
我试着写一个Rails控制器方法,将响应同时获得正常(如下面的链接),并通过AJAX提出了要求。
I'm trying to write a Rails controller method that will respond to get requests made both "normally" (e.g. following a link) and via ajax.
常规情形:控制器应使用布局完全装修HTML响应
Normal Case: The controller should respond with fully decorated HTML using the layout.
阿贾克斯案例:电脑板应与HTML响应片断由模板生成的(没有布局)
Ajax Case: The conroller should respond with the HTML snippet generated by the template (no layout)
下面是jQuery的code,我创建在客户端运行,做get请求。
Here's the jQuery code, I've created to run on the client side to do the get request.
jQuery.get("http://mydomain.com/some_controller/some_action",
{},
function(data, textstatus) {
jQuery("#target").html(data);
},
"html");
什么是处理这个Rails中的最佳方法是什么?
What's the best way to handle this in Rails?
推荐答案
在你的控制器动态地选择是否使用基于 request.xhr?
的布局。
In your controller dynamically select whether to use a layout based on request.xhr?
.
例如:
class SomeController < ApplicationController
layout :get_layout
protected
def get_layout
request.xhr? ? nil : 'normal_layout'
end
end
这篇关于如何通过AJAX Rails中取得HTML请求作出回应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!