简体   繁体   English

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

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

In my rails app I send request in html, ajax, xml and json. 在我的Rails应用程序中,我以html,ajax,xml和json发送请求。 For xml and json I do it by writing :format => 'json/xml', for ajax we write :remote => true. 对于xml和json,我通过编写:format =>'json / xml'来实现,对于ajax,我们编写了:remote => true。

But how server know that it has to respond with ajax, xml or json? 但是服务器如何知道它必须使用ajax,xml或json响应? One thing I noticed when I send json or xml request it show in the url like below 我发送json或xml请求时注意到的一件事,它显示在url中,如下所示

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

Though Im not sure, this is how server know if he has to give json response. 尽管我不确定,但这是服务器知道他是否必须提供json响应的方式。 But for html and ajax something like this is don't add in the url. 但是对于html和ajax,不要在URL中添加类似的内容。 So how server know whether it is ajax or html request? 那么服务器如何知道它是ajax还是html请求呢?

Request headers are governed by mime-types , which basically determine which type of content / request is being sent 请求标头由mime-types控制 ,它基本上确定要发送的内容/请求的类型

Rails has an in-built handler to manage different responses. Rails具有内置的处理程序来管理不同的响应。 As per @hawk's URL on ActionDispatch::Request , you can see this middleware essentially catches the type of request sent from the browser 根据ActionDispatch :: Request@hawk的URL,您可以看到此中间件实际上捕获了浏览器发送的请求类型


Respond_To 回应

The real answer to your question is about the respond_to block: 您问题的真正答案是关于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

This will allow you to send various responses depending on the mime-type sent in the request :) 这将允许您根据请求中发送的mime类型发送各种响应:)

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

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