Ruby(RoR) Tip3: Send and Receive JSON

40 sec read

Making a JSON request using jQuery can be sent to a controller in two ways.

[source language=”javascript”]
$.getJSON(‘http://localhost:3000/members/try_this’, function(data) {
alert(data[0].member.name);
});
[/source]
or
[source language=”javascript”]
$.ajax({
type: ‘get’,
url: “/members/try_this”,
data: ”,
dataType: ‘json’,
context: document.body,
success:function(response){
alert(response[0].member.name);
}
});
[/source]
The JSON request can be seen in the Net-XHR tab of Firebug. Firebug is a great tool for web development. They also facilitate exploring JSON responses, requests. The JSON tab can be seen for a JSON request. The content-type of the request in Firebug shows that the request was a JSON request. This is how it would look.
firebug-scrnshot-12
The controller method that would return a JSON response would look like this.
[source language=”ruby”]
def try_this
@members = Member.all
respond_to do |format|
format.json { render :json => @members}
end
end
[/source]
Here the controller also returns a JSON object. The JSON response would look like this when viewed in the JSON tab of the Firebug console.
firebug-scrnshot-22
Hope you like it, if you have any other suggestions please leave a comment.

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *