简体   繁体   English

Rails中的“ respond_to”

[英]Rails “respond_to” in PHP

Lately I have been trying out Rails, and I came to love the respond_to. 最近,我一直在尝试Rails,后来我开始喜欢response_to。

Is it possible to do something like this in PHP?, responding to different types of requests. 是否可以在PHP中执行类似的操作?以响应不同类型的请求。 So it is easy to implement an alternate way even if javascript is disabled. 因此,即使禁用了javascript,也很容易实现替代方法。

You can dispatch on the filename suffix as Krule suggests, but I believe Rails determines which content type to choose by examining the value of the HTTP Accept header (see Content negotiation on Wikipedia). 您可以按照Krule的建议在文件名后缀上分派,但我相信Rails可以通过检查HTTP Accept标头的值来确定选择哪种内容类型(请参阅Wikipedia上的内容协商 )。 In pseudo-code 用伪代码

$data = fetch_some_data();
switch (get_preferred_response_type($_SERVER['HTTP_ACCEPT'])) {
    case 'text/html':
       render_html($data); break;
    case 'application/xml':
       render_xml($data);
    case 'application/json':
       render_json($data);
    // etc...
}

The get_preferred_response_type() function will have to parse the Accept header and return the client's preferred MIME type. get_preferred_response_type()函数将必须解析Accept标头并返回客户端的首选MIME类型。 Here is an example of such a function which should help you get started; 是一个可以帮助您入门的函数示例。 otherwise there is a content negotiation library for PHP which does all the dirty work for you. 否则,将为PHP提供一个内容协商库 ,该可以为您完成所有繁琐的工作。

Hope this helps! 希望这可以帮助!

Last time I did something similar to respond_to in Rails I used Apache .htaccess RewriteRule in order to process GET variables to php. 上次我在Rails中执行了类似于respond_to ,我使用Apache .htaccess RewriteRule来处理GET变量到php。 Something like this: 像这样:

RewriteEngine on
RewriteRule (\d*\.?\d*?).(html|json|xml|txt) /file.php?format=$1

I hope it helps at least a bit. 我希望它至少可以有所帮助。 Good luck. 祝好运。

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

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