简体   繁体   English

Rails 3-即使请求格式为text / html,控制器也使用javascript进行响应

[英]rails 3 - controller respond with javascript even through request format was text/html

I have a simple scenario where I want to request a page. 我有一个简单的场景,我想请求一个页面。 The request format is text/html. 请求格式为text / html。 If there is some error in the controller/action logic for that request, I want to get an error message. 如果该请求的控制器/操作逻辑中有错误,我想得到一条错误消息。 The twist is that I want this error message to be communicated to be with a javascript response type (ie no page refresh). 问题是我希望将此错误消息与javascript响应类型进行通信(即无页面刷新)。 If there are no errors, then I want the page to be loaded via the expected text/html response type. 如果没有错误,那么我希望通过预期的text / html响应类型加载页面。

Basically, I want two different response types depending on whether there is an error or not. 基本上,我要根据是否有错误来选择两种不同的响应类型。 Is this doable in rails 3? 这在rails 3中可行吗? If so, what is best practice? 如果是这样,什么是最佳做法?

A quick code sample would be much appreciated. 快速代码示例将不胜感激。

Thanks. 谢谢。

Sure it's doable! 当然可以!

I would do it like this: 我会这样做:

def some_action
  # code
  # more code
  # implicit or explicit rendering of an html template
rescue Exception => ex
  render :json => ex.to_json, 
         :content_type => 'application/json',
         :layout => false
end

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

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