【问题标题】:How to send simple json response in Rails?如何在 Rails 中发送简单的 json 响应?
【发布时间】:2012-09-05 07:21:07
【问题描述】:

我需要发送 json 响应取决于用户在输入中输入的数据,但我无法发送简单的 json 请求。

我关注了这篇文章 - http://paydrotalks.com/posts/45-standard-json-response-for-rails-and-jquery

添加了 MimeType:

Mime::Type.register_alias "application/json", :jsonr, %w( text/x-json )  

在我的控制器中:

 def checkname
  respond_to do |format|
    format.jsonr do
      render :json => { 
         :status => :ok, 
         :message => "Success!",
         :html => "<b>congrats</b>"
      }.to_json
     end  
  end
end

但是屏幕是空的,当我对此操作编写 GET 响应时,这是来自 fiddler2 的响应代码:

    HTTP/1.1 406 Not Acceptable
   Content-Type: text/html; charset=utf-8
   X-UA-Compatible: IE=Edge
   Cache-Control: no-cache
   X-Request-Id: 14a8467908d9ce322d054607efdacf92
   X-Runtime: 0.011000
   Content-Length: 1
   Connection: keep-alive
  Server: thin 1.4.1 codename Chromeo

我做错了什么?

【问题讨论】:

  • 您确定在 mime_types.rb 版本后重新启动了您的应用程序吗?并确保您通过带有.jsonr 的网址访问您的操作,例如:http://localhost:3000/checkname.jsonr
  • @jdoe,是的。你说的对。你能看这里吗stackoverflow.com/questions/12382680/… - 这就是我需要发送 json 请求的原因。
  • 我到底在哪里? :) 你解决了问题还是仍然存在?我尝试了您的代码并将浏览器指向 http://localhost:3000/checkname.jsonr 给了我 JSON 响应(应用程序/json)。
  • 是的,它对我有用。添加.jsonr。你能看看上面发布的问题的链接吗?
  • 我看了看那些帖子。看起来您希望您的操作默认触发您的 format.jsonr 块(如果您只是请求 /checkname)。我说的对吗?

标签: ruby-on-rails json


【解决方案1】:

最简单的方法是render json: {foo: 'bar'}

【讨论】:

    【解决方案2】:

    一个简单的方法是:

    def my_action 
    
     render :json => {:name => "any name"}
    
    end
    

    【讨论】:

      【解决方案3】:

      我一般用这种方式返回json数据:

      msg = {:token => token, :courseId => courseId}
      render :json => msg
      

      【讨论】:

      • 这很简单!
      【解决方案4】:

      不确定如何处理自定义 MIME,但对于呈现 JSON,这应该可以:

      def testme
        respond_to do |format|
          msg = { :status => "ok", :message => "Success!", :html => "<b>...</b>" }
          format.json  { render :json => msg } # don't do msg.to_json
        end
      end
      

      如果您说明您使用的是哪个版本的 Ruby 和 Rails,这可能会有所帮助。

      【讨论】:

      • 我不知道为什么,但是您的代码对我不起作用。我的版本正在运行render :json =&gt; { :status =&gt; :ok, :message =&gt; "Success!", :html =&gt; "...insert html..." }
      • @MID 您是否在控制器顶部包含respond_to :html, :json
      猜你喜欢
      • 2019-10-09
      • 2016-04-03
      • 2014-01-22
      • 1970-01-01
      • 2011-08-26
      • 2018-12-12
      • 1970-01-01
      • 1970-01-01
      • 2011-09-07
      相关资源
      最近更新 更多