Saturday, 15 October 2011

Call JSONP with jQuery

In order to call JSONP with jQuery, please use following code

function jsonp() {

  this.request = function(url, args, callbackVar, bufferID) {
    var super = this;
    var callback = 'jsonp_response_' + Math.floor(Math.random() * 100000);
    window[callback] = function(data) {
      super.response(args, data);
      delete window[callback];
    }
    var params = { callbackVar : callback };
    var buffer = $('#' + bufferID);
    buffer.append("<script src='" + url + '&' + jQuery.param(params) + "'></script>");
  }

  this.response = function(args, data) {
  }

}

callbackVar: name of GET variable containing JSONP callback, eg. api.php?jsonp=response
bufferID: id of empty div tag which is used for temporarily adding script tag
args: arguments is passed to callback function

No comments:

Post a Comment