April 9, 2020
Estimated Post Reading Time ~

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

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>


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.