How to use $.getJSON() method of jQuery with grails?

02 / Mar / 2009 by Chandan Luthra 4 comments

How to use $.getJSON() method of jQuery with grails?

Retriving a JSON string from Grails is very easy. You have to just write the following in your controller’s action

Let me explain you with an example of populating a HTML table using JSON response:
In this example, we have table with columns – name,address and gender. We want the table to be populated without doing a full page refresh, using an Ajax call.

Domain Class:

class MyDomain {
    String name
    String address
    String gender
}

Controller Class :

class MyController {
   def someaction = {
      List myDomains = MyDomain.findAllByGender(params.gender)
      /*Let say 5 objects are retrieved*/
      render myDomains as JSON
   }
}

The above code in action will render a JSON string in the following format:

[
{
"name" : "John",
"address" : "New York",
"gender" : "Male"
},
{
"name" : "Rob",
"address" : "Indonasia",
"gender" : "Male"
},
{
"name" : "Shayam",
"address" : "New Delhi",
"gender" : "Male"
},
{
"name" : "Chang",
"address" : "Thailand",
"gender" : "Male"
},
{
"name" : "Ali",
"address" : "London",
"gender" : "Male"
}
]

following script would be writtent on the client Side (in the GSP):

The HTML code would be like this :

<div id=”someid”>
Click for JSON Response
</div>
<table id=”mytable”>
<!–empty table –>
</table>

When you click on the displayed text the html page would become like following:

<div id="someid">
Click for JSON Response
</div>
<table id="mytable">
<tr>
<td>John</td>
<td>New York</td>
<td>Male</td>
</tr>
<tr>
<td>Rob</td>
<td>Indonasia</td>
<td>Male</td>
</tr>
<tr>
<td>Shayam</td>
<td>New Delhi</td>
<td>Male</td>
</tr>
<tr>
<td>Chang</td>
<td>Thailand</td>
<td>Male</td>
</tr>
<tr>
<td>Ali</td>
<td>London</td>
<td>Male</td>
</tr>
</table>

any kind of suggestions and comments are welcome……

Regards,
Chandan Luthra

http://www.tothenew.com

FOUND THIS USEFUL? SHARE IT

comments (4)

  1. sr

    thanks for your example, here we have written the view in GSP. Is it possible that we donot use any GSP tags and build the view in html, css and javascript and have *.html files on grails server and ask server to redirect them, if yes, what changes will be required in UrlMappings.groovy file?

    Reply

Leave a Reply

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