1

我正在向 php 文件发出请求。响应在 .done(function(msg){}) 中处理;和 .fail 这工作正常。但有时请求会出错。我为此重试了一次。重试也有效。但是,如果第一次失败并且在 de 2 或 3 中成功,请尝试我的 request.done 不会触发(在 firebug 中我可以看到它是成功的)

我的请求:

    var request = $.ajax({    
                url:            "wcf.php",            
                type:           "POST",     
                dataType:       "xml",
                async:          false,
                timeout:        5000,
                tryCount:       0,
                retryLimit:     3,
                data:      { barcode: value, curPrxID: currentPrxID, timestamp: (new Date).getTime()},
                error: function (xhr, ajaxOptions, thrownError) {
                    if (xhr.status == 500) {
                        alert('Server error');
                    } 
                        this.tryCount++;
                        if (this.tryCount < this.retryLimit) {
                            $.ajax(this);
                            //return;
                        }
                }
           }) ;  

这是 .done 和失败:

request.done(function(msg) 
{
    $(msg).find("Response").each(function()
    {
             // my code here
    });
});

request.fail(function(jqXHR, textStatus, errorThrown) 
{ 
    $("#message").html(errorThrown);    
});
4

1 回答 1

1

.done().fail()方法是延迟对象的一部分,它在 .jqXHR返回的对象中实现$.ajax()。您向他们注册的回调不是选项的一部分, $.ajax()因此您不能将它们传递给另一个$.ajax(). 在您的代码中,您仅订阅父$.ajax() 延迟对象回调。为了达到您想要的结果,您应该将整个操作包装在另一个延迟对象中并使用.resolveWith()/.rejectWith()方法来传递正确的上下文。您还需要记住延迟对象可以将其状态更改为已解决或已拒绝只有一次(换句话说,如果它失败了,以后就不能成功)。所以最终的代码可能是这样的:

var request = $.Deferred(function(deferred) {
    $.ajax({    
        url: 'wcf.php',
        type: 'POST',
        dataType: 'xml',
        async: false,
        timeout: 5000,
        tryCount: 0,
        retryLimit: 3,
        data: { barcode: value, curPrxID: currentPrxID, timestamp: (new Date).getTime()},
        error: function (xhr, ajaxOptions, thrownError) {
            if (xhr.status == 500) {
                alert('Server error');
            }
            this.tryCount++;
            if (this.tryCount < this.retryLimit) {
                $.ajax(this).done(function(data, textStatus, jqXHR) {
                    deferred.resolveWith(this, [data, textStatus, jqXHR]);
                }).fail(function(jqXHR, textStatus, errorThrown) {
                    if (this.tryCount >= this.retryLimit) {
                        deferred.rejectWith(this, [jqXHR, textStatus, errorThrown]);
                    }
                });
            }
        }
    }).done(function(data, textStatus, jqXHR) {
        deferred.resolveWith(this, [data, textStatus, jqXHR]);
    });
}).promise();

request.done(function(msg) {
    $(msg).find("Response").each(function() {
        //Success code here
    });
});

request.fail(function(jqXHR, textStatus, errorThrown) { 
    $("#message").html(errorThrown);
});
于 2013-07-22T09:57:11.050 回答