开发者

jquery ajax failed request not triggering complete or error handler

I'm making an ajax call like this:

var requestData = function() {
    $.ajax({
        dataType: 'jsonp',
        jsonp: 'js',
        url: "http://someS开发者_开发百科erver", 
        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
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜