【问题标题】:How to send json request to rails app如何向 Rails 应用程序发送 json 请求
【发布时间】:2014-05-20 07:46:50
【问题描述】:

我想从带有文本区域的 HTML 页面发送一些 json 参数,并且我想发送写在这个文本区域中的 json 参数,例如格式。 {"name": "test", "description":"test", "price":100}

但是 rails 认为它​​是{"{'name' : 'test', 'description' : 'test', 'price' : 100}"=>nil} 我如何从文本区域发送 json 参数以从 rails 应用程序读取。

【问题讨论】:

  • 你能把发送jsoncode贴出来吗?
  • 你设置了吗?内容类型:application/json (hashcode.eti.br/?p=481)
  • 当你提到你正在“发送”JSON 参数时——你是怎么做到的?你能详细说明你是如何发送它们的吗?
  • 是的,我设置了 Content-Type: application/json 但 rails 不理解从文本区域(json 格式)传递的内容。你可以从这个示例中轻松理解<input type='textarea' name='content' value='{"name": "test", "description":"test", "price":100}' id='text_content' />

标签: ruby-on-rails ruby ajax json ruby-on-rails-3


【解决方案1】:

我认为您需要在服务器端使用 JSON.parse 解析该字符串

param = '{"name" : "test", "description" : "test", "price" : 100}'
# assume you got the param on server side
json_param = JSON.parse(param)
puts json_param['name']

【讨论】:

    【解决方案2】:

    正如你在评论中所说:

    您可以从这个示例中轻松理解:

    <input type='textarea' name='content' value='{"name": "test", "description":"test", "price":100}' id='text_content' />
    

    你刚刚以这种方式向 Rails 发送了一个字符串。

    如果您使用表单提交,您应该为不同的参数使用不同的输入。

    如果是 Javascript,也许是 jQuery,你可以使用函数 $.post

    Rails 会为您解析 json。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-08
      • 2018-12-20
      • 2011-08-05
      • 2014-02-19
      • 1970-01-01
      • 2020-01-07
      • 1970-01-01
      • 2012-06-11
      相关资源
      最近更新 更多