What exactly do you want to know? ActiveRecord has methods that serialize entries in JSON. For example, open the rails console and enter ModelName.all.to_json and you will see the JSON output. render :json essentially calls to_json and returns the result to the browser with the correct headers. This is useful for AJAX calls in JavaScript, where you want to return JavaScript objects for use. Alternatively, you can use the callback option to specify the name of the callback you want to call through JSONP.
For example, let's say we have a User model that looks like this: {name: 'Max', email:' m@m.com'}
We also have a controller that looks like this:
class UsersController < ApplicationController def show @user = User.find(params[:id]) render json: @user end end
Now, if we call an AJAX call using jQuery as follows:
$.ajax({ type: "GET", url: "/users/5", dataType: "json", success: function(data){ alert(data.name)
As you can see, we managed to get User with id 5 from our rails application and use it in our JavaScript code, because it was returned as a JSON object. The callback option simply calls the JavaScript function named named, passed with the JSON object, as the first and only argument.
To give an example callback parameter, look at the following:
class UsersController < ApplicationController def show @user = User.find(params[:id]) render json: @user, callback: "testFunction" end end
Now we can request a JSONP request as follows:
function testFunction(data) { alert(data.name); // Will alert Max }; var script = document.createElement("script"); script.src = "/users/5"; document.getElementsByTagName("head")[0].appendChild(script);
The motivation for using this callback is usually to bypass browser protection, which restricts cross-resource sharing (CORS). However, JSONP is no longer used because there are other methods to bypass CORS that are more secure and easier.