Anatomy of JSONP Ajax in GWT
It is just a self study note from http://code.google.com/webtoolkit/doc/latest/tutorial/Xsite.html
Part 1: Cross site JSON web service
So in my case I deployed the stockPrices.php onto my development php server and a call to:
http://localhost:81/AliasTestSite/stockPrices.php?q=ABC&callback=callback125
gives me a JSONP string:
callback125([{“symbol”:”ABC”,”price”:68.826522738023,”change”:-1.3483844858836}]);
Part 2 : JSONP url
private static final String JSON_URL = "http://localhost:81/AliasTestSite/stockPrices.php?q=";
Part 3: Data contract
The same as JSON example
Part 4: Request
As it is cross site, JSONP call has to be in src of
<script>
element, it is implemented in a JSNI method called getJson. It does a couple of things:
Create a script element on fly, set the JSONP call in the src , inject the new script element into dom.
When jsonp is returned, callback wrapper is triggered, the wrapper sends the json object to Java method handleJsonResponse, sets the call back status flag
window[callback + “done”] = true
the call back status flag will be picked up by a timer, when it is true, getJson will clean up by deleting dynamic script element and call back wrapper functions.
/**
* Make call to remote server.
*/
public native static void getJson(int requestId, String url,
StockWatcher handler) /*-{
var callback = "callback" + requestId;
// [1] Create a script element.
var script = document.createElement("script");
script.setAttribute("src", url+callback);
script.setAttribute("type", "text/javascript");
// [2] Define the callback function on the window object.
window[callback] = function(jsonObj) {
// [3]
handler.@com.google.gwt.sample.stockwatcher.client.StockWatcher::handleJsonResponse(Lcom/google/gwt/core/client/JavaScriptObject;)(jsonObj);
window[callback + "done"] = true;
}
// [4] JSON download has 1-second timeout.
setTimeout(function() {
if (!window[callback + "done"]) {
handler.@com.google.gwt.sample.stockwatcher.client.StockWatcher::handleJsonResponse(Lcom/google/gwt/core/client/JavaScriptObject;)(null);
}
// [5] Cleanup. Remove script and callback elements.
document.body.removeChild(script);
delete window[callback];
delete window[callback + "done"];
}, 1000);
// [6] Attach the script element to the document body.
document.body.appendChild(script);
}-*/;
Tags: GWT
