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. How do I access this data in 开发者_如何学编程my controller (I'm using Ruby on Rails).
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.
Example using jQuery:
$.ajax({
url:'/some_url',
data: {user: {name:"Bob", email: "bob@example.com"}},
dataType: 'json',
type: 'POST'
});
Access the parameter through the params hash. There should be no need to decode JSON. Rails should convert it into a hash for you.
精彩评论