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

发布于 2024-12-25 19:43:16 字数 256 浏览 1 评论 0原文

我有一个简单的场景,我想请求一个页面。请求格式为text/html。如果该请求的控制器/操作逻辑中有一些错误,我想收到一条错误消息。不同的是,我希望通过 JavaScript 响应类型(即没有页面刷新)来传达此错误消息。如果没有错误,那么我希望通过预期的 text/html 响应类型加载页面。

基本上,我想要两种不同的响应类型,具体取决于是否存在错误。这在 Rails 3 中可行吗?如果是这样,最佳实践是什么?

快速的代码示例将不胜感激。

谢谢。

I have a simple scenario where I want to request a page. The request format is 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 (i.e. no page refresh). If there are no errors, then I want the page to be loaded via the expected text/html response type.

Basically, I want two different response types depending on whether there is an error or not. Is this doable in rails 3? If so, what is best practice?

A quick code sample would be much appreciated.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁吢 2025-01-01 19:43:16

当然是可行的!

我会这样做:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文