Sample Client Program:
$(function(){
$('#searchForm').submit(function(){
var url = 'http://someremotesite.com/search/index?q=test&id=10&callback=?';
$.getJSON(url, null, function(data) {
alert('Result = '+data['result']);
});
return false;
});
});
The most important part is the string "callback=?" added to the end of the URL(see line 3 of program above) makes jQuery to recognise it as a JSONP call. What it basically does is that it supplies the name of the default handler for the AJAX call by storing it in the variable "callback" which we use on the server side.Sample Server Program:
import grails.converters.JSONThe last line(line 11) prints the default assigned callback function along with the JSON data as its parameter. For example, if the default callback function assigned by jQuery is "handleOutput" and jsonData is the "result" object rendered as JSON in above example then Grails renders the output as: handleOutput(jsonData).
class SearchController {
def index = {
//do some thing
def result = someCalculation()
render "${params.callback}(${result as JSON})"
}
}
The returned JSON object can be manipulated in the same manner as we manipulate any other JSON objects using javascript.
Hope this helps someone out there.
Keep on coding.