-
-
Save heisters/215601 to your computer and use it in GitHub Desktop.
an alternative to jQuery's JSONP method with basic error handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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