-
-
Save malsup/82181 to your computer and use it in GitHub Desktop.
// 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); | |
} | |
}; |
http://stackoverflow.com/questions/8627201/ajax-upload-plugin-throwing-jquery-handleerror-not-found
Above version 1.5 of jQuery, the function $.handleError is undefined. Defining this function solves the problem (solved for me). I'm not aware of a better solution to jsonp.
$.handleError = function(s, xhr, status, e) {
// If a local callback was specified, fire it
if ( s.error ) {
s.error.call( s.context || window, xhr, status, e );
}
// Fire the global callback
if ( s.global ) {
(s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
}
};
Since my solution must be compatible with IE8, this is a good work-around. But, if you can use $.get, do so.
I'm getting an error because the callback name is not set on the URL, it is still "?". The original getJSON function changes that to a random name. I'm using jquery 1.11.0
XMLHttpRequest cannot load http://localhost:8090/ehr/rest/ehrForSubject?subjectUid=&format=json&callback=?. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 400.
the clause at line 39 fails for me under jquery 1.7.1. both$.ajax.handleError and $ .handleError return 'undefined'. any idea how best to update this to run under jquery 1.7?