简体   繁体   English

您如何访问通过 AJAX 请求发布的 Rails controller 上的 Ruby 中的数据?

[英]How do you access data in a Ruby on Rails controller that is POSTed via an AJAX request?

I'm sending an AJAX request and posting some json data to the server.我正在发送 AJAX 请求并将一些 json 数据发布到服务器。 How do I access this data in my controller (I'm using Ruby on Rails).如何在我的 controller 中访问这些数据(我在 Rails 上使用 Ruby)。

It should be trivial:它应该是微不足道的:

data = ActiveSupport::JSON::decode(params[:param_with_json_string])

If you set the Content-Type of the post request to application/json then Rails will handle things for you and make the data available in the params hash like normal.如果您将 post 请求的 Content-Type 设置为application/json ,那么 Rails 将为您处理事情,并像往常一样在参数 hash 中提供数据。

Example using jQuery:使用 jQuery 的示例:

$.ajax({
  url:'/some_url', 
  data: {user: {name:"Bob", email: "bob@example.com"}}, 
  dataType: 'json',
  type: 'POST'
});

Access the parameter through the params hash.通过参数 hash 访问参数。 There should be no need to decode JSON.应该不需要解码 JSON。 Rails should convert it into a hash for you. Rails 应该为您将其转换为 hash。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM