Light JSONP implementation

Since we are doing a cross origin JSON request, and GAS does not support CORS, we have to use JSONP. To know more about JSONP see JSONP and JSON and Google Apps Script webapps.

Here's an example of a very simple non blocking JSONP implementation.

function getData(siteCode, appUrl) {

  //create a script element to hold jsonp response
  var script = document.createElement('script');

  // construct the url
  script.src = appUrl + "?" + [
    "sitecode=" + siteCode,
    "page=" + encodeURIComponent(document.referrer),
    "callback=response"
    ].join("&");
  document.body.appendChild(script);

}
function response(result) {

  // gets called when the jsonp script is loaded and executed
  if (!result.data ) {
    console.log ( 'error - no data(' + JSON.stringify(result) + ")");
  }

  //do something with the data
  doIt(result.data);
}


We need to pass the current page to Retrieving page data from GAS web service we need to figure out what page we are on. Since gadgets run in an Iframe, document.referrer will be pointing to the current page. Passing this will cause a JSONP response with the stats for that page.


For help and more information join our forum,follow the blog or follow me on twitter .


Comments