Skip to content

Instantly share code, notes, and snippets.

@heisters
Forked from malsup/jsonp
Created October 22, 2009 00:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heisters/215601 to your computer and use it in GitHub Desktop.
Save heisters/215601 to your computer and use it in GitHub Desktop.
an alternative to jQuery's JSONP method with basic error handling
// fn to handle jsonp with timeouts and errors
// hat tip to Ricardo Tomasi for the timeout logic
$.getJSONP = function(s) {
s.dataType = 'jsonp';
$.ajax(s);
var t = 0, cb = s.url.match(/callback=(\w+)/)[1], cbFn = window[cb];
var $script = $('head script[src*='+cb+']');
if (!$script.length)
return; // same domain request
$script[0].onerror = function(e) {
$script.remove();
$.handleError(s, {}, "error", e);
clearTimeout(t);
};
if (!s.timeout)
return;
window[cb] = function(json) {
clearTimeout(t);
cbFn(json);
cbFn = null;
};
t = setTimeout(function() {
$script.remove();
$.handleError(s, {}, "timeout");
if (cbFn)
window[cb] = function(){};
}, s.timeout);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment