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.
It did help someone out there.
ReplyDeleteKind regards from Berlin
Exactly what I was looking for. If you want to remove the warning regarding context type replace line #11 with:
ReplyDeletedef converter = result as JSON
render(text: "${callback}(${converter})", contentType: "application/javascript", encoding: "UTF-8") }
or if you want to use google-gson:
Gson gson = new Gson()
if (callback) { render(text: "${callback}(${gson.toJson(result)})", contentType: "application/javascript", encoding: "UTF-8") }
else { render(text: gson.toJson(result), contentType: "application/json", encoding: "UTF-8") }
The above example will return JSON if callback isn't set. If callback is set then JSONP is returned.