Anatomy of JSONP Ajax in GWT

It is just a self study note from

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:

gives me a JSONP string:

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


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];)(jsonObj);
     window[callback + "done"] = true;

   // [4] JSON download has 1-second timeout.
   setTimeout(function() {
     if (!window[callback + "done"]) {;)(null);

     // [5] Cleanup. Remove script and callback elements.
     delete window[callback];
     delete window[callback + "done"];
   }, 1000);

   // [6] Attach the script element to the document body.


This entry was posted on Friday, July 29th, 2011 at 3:20 am and is filed under Java, Javascript. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply