【问题标题】:rails 3 - controller respond with javascript even through request format was text/htmlrails 3 - 即使请求格式为 text/html,控制器也会使用 javascript 响应
【发布时间】:2012-01-09 09:49:40
【问题描述】:

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

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

非常感谢您提供快速代码示例。

谢谢。

【问题讨论】:

    标签: ruby-on-rails model-view-controller


    【解决方案1】:

    当然可以!

    我会这样做:

    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
    

    【讨论】:

      猜你喜欢
      • 2020-04-09
      • 2014-09-03
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      • 2017-01-07
      • 2019-06-13
      • 1970-01-01
      • 2020-10-01
      相关资源
      最近更新 更多