public
Last active

  • Download Gist
jsonp.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
/* jsonp.js for Protototype
*
* Copyright (c) 2009 Tobie Langel (http://tobielangel.com)
*
* jsonp.js is freely distributable under the terms of an MIT-style license.
*--------------------------------------------------------------------------
Requires: Prototype >= 1.6
Usage:
new Ajax.JSONRequest('http://api.flickr.com/services/feeds/photos_public.gne', {
onComplete: function(json) {
console.log(json)
},
callbackName: 'jsoncallback',
parameters: {
tags: 'cat',
tagmode: 'any',
format: 'json'
}
});
*/
 
Ajax.JSONRequest = Class.create(Ajax.Base, (function() {
var id = 0, head = document.getElementsByTagName('head')[0];
return {
initialize: function($super, url, options) {
$super(options);
if (!this.options.callbackName) {
this.options.callbackName = 'callback';
}
this.request(url);
},
request: function(url) {
var callbackName = '_prototypeJSONPCallback_' + (id++),
self = this,
script;
 
this.options.parameters[this.options.callbackName] = callbackName;
url += (url.include('?') ? '&' : '?') + Object.toQueryString(this.options.parameters);
window[callbackName] = function(json) {
script.remove();
script = null;
window[callbackName] = undefined;
if (self.options.onComplete) {
self.options.onComplete.call(self, json);
}
}
script = new Element('script', {
type: 'text/javascript',
src: url
});
head.appendChild(script);
}
};
})());

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.