繁体   English   中英

服务器如何响应Rails应用程序的html,ajax,xml和json

[英]How server respond for html, ajax, xml and json for rails app

在我的Rails应用程序中,我以html,ajax,xml和json发送请求。 对于xml和json,我通过编写:format =>'json / xml'来实现,对于ajax,我们编写了:remote => true。

但是服务器如何知道它必须使用ajax,xml或json响应? 我发送json或xml请求时注意到的一件事,它显示在url中,如下所示

http://localhost:3000/en/line_items.json

尽管我不确定,但这是服务器知道他是否必须提供json响应的方式。 但是对于html和ajax,不要在URL中添加类似的内容。 那么服务器如何知道它是ajax还是html请求呢?

请求标头由mime-types控制 ,它基本上确定要发送的内容/请求的类型

Rails具有内置的处理程序来管理不同的响应。 根据ActionDispatch :: Request@hawk的URL,您可以看到此中间件实际上捕获了浏览器发送的请求类型


回应

您问题的真正答案是关于respond_to块:

#apps/controller/your_controller.rb
def new
    respond_to do |format|
        format.html { # do stuff here }
        format.js { # do stuff here }
        format.json { # do stuff here }
    end
end

这将允许您根据请求中发送的mime类型发送各种响应:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM