Ruby-on-rails 如何在 Rails 中发送简单的 json 响应?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12385345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:44:18  来源:igfitidea点击:

How to send simple json response in Rails?

ruby-on-railsjson

提问by MID

I need to send json response depends on user entered data in input, but I'm failing to send simple json request.

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

I followed this article - http://paydrotalks.com/posts/45-standard-json-response-for-rails-and-jquery.

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

Added MimeType:

添加了 MimeType:

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

and in my controller:

在我的控制器中:

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

but the screen is empty and here is response code from fiddler2 when I composed GET response to this action:

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

    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

What I'm doing wrong ?

我做错了什么?

回答by Lukas Stejskal

Not sure about dealing with custom MIME, but as for rendering JSON, this should work:

不确定处理自定义 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

Also it might help if you state which version of Ruby and Rails you are using.

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

回答by dalmate

I usually use this method to return json data:

我通常使用这种方法返回json数据:

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

回答by Somesh Sharma

One Simple way is:

一种简单的方法是:

def my_action 

 render :json => {:name => "any name"}

end

回答by Elvack Riansyah

The simplest way is render json: {foo: 'bar'}

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