Monday, May 10, 2010

Grails Return JSON

Domain Class:

class MyDomain {


String name


String address


String gender

}

Controller Class :

class MyController {


def someaction =
{


List myDomains = MyDomain.findAllByGender(params.gender)


<em>/*Let say 5 objects are retrieved*/</em>

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):

<script>

$.document.ready(function(){

$('#someid').click(function(){

<strong>$.getJSON</strong>("${createLink(controller:'my',action:'someaction')}",{gender:'Male', ajax:
'true'},
function(myDomains){

var myHTMLString =
''

for(var i =
0
; i < myDomains.length
; i++)

{

myHTMLString = myHTMLString +
'<tr><td>'
+ myDomains[i].name
+
'</td>'

myHTMLString = myHTMLString +
'<tr><td>'
+ myDomains[i].address
+
'</td>'

myHTMLString = myHTMLString +
'<tr><td>'
+ myDomains[i].gender
+
'</td></tr>'

}

$('table#mytable').html(myHTMLString)

})

})

})

</script>


 

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……

No comments:

Post a Comment