Skip to content

Instantly share code, notes, and snippets.

@Qijiang60
Forked from malsup/jsonp
Created March 3, 2017 18:57
Show Gist options
  • Save Qijiang60/cb9bf04f5bea14832467ef81143a9d2e to your computer and use it in GitHub Desktop.
Save Qijiang60/cb9bf04f5bea14832467ef81143a9d2e to your computer and use it in GitHub Desktop.
$.getJSONP
// 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);
// figure out what the callback fn is
var $script = $(document.getElementsByTagName('head')[0].firstChild);
var url = $script.attr('src') || '';
var cb = (url.match(/callback=(\w+)/)||[])[1];
if (!cb)
return; // bail
var t = 0, cbFn = window[cb];
$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);
function handleError(s, o, msg, e) {
// support jquery versions before and after 1.4.3
($.ajax.handleError || $.handleError)(s, o, msg, e);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment