I'm making an ajax call like this:
var requestData = function() {
$.ajax({
dataType: 'jsonp',
jsonp: 'js',
url: "http://someServer",
success: function (data) {
// do stuff with data
},
complete : function(data) {
// try again in 5 seconds
setTimeout(requestData, 5000);
}
});
};
All is well and good, and it works, EXCEPT: the server is a bit flaky, and from time to time, it fails to return a response. That's fine, but when that happens, the complete handler never fires. I've also tried using an error handler. Is there something else I can do? I've thought about using setInterval, but I'd really rather it do the next one after this one, not at a set time where they might pile up....
UPDATE: when the server fails, I get "Failed to load resource" in chrome's console.
The problem is that JSONP works by inserting a script
tag into the DOM, rather than by XMLHTTPRequest. script
tags have no onerror
property, so you can't test for success by conventional methods. The only way to do it is via a timeout.
Something like this might work:
var requestComplete = {};
var requestData = function() {
var now = (new Date()).getTime();
requestComplete[now] = false;
$.ajax({
dataType: 'jsonp',
jsonp: 'js',
url: "http://someServer",
success: function (data) {
requestComplete[now] = true;
// do stuff with data
}
});
setTimeout(function() {
if (!requestComplete[now]) {
setTimeout(requestData, 5000); // try again in 5 seconds
}
}, 5000); // give the JSONP request 5 seconds to work
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.