jQuery:处理失败的AJAX请求的后备

Pat*_*ity 37 ajax jquery json callback wait

jQuery可以为失败的AJAX调用提供回退吗?这是我的尝试:

function update() {
    var requestOK = false;

    $.getJSON(url, function(){
        alert('request successful');
        requestOK = true;
    });

    if (!requestOK) {
        alert('request failed');
    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,即使调用$ .getJSON()方法的回调函数,在回调函数有机会设置requestOK变量之前,我得到消息'request failed'.我认为这是因为代码并行运行.有没有办法处理这种情况?我想过链接或某种等待AJAX​​请求的方式,包括它的回调函数.但是怎么样?有谁知道这是怎么做到的吗?

Dou*_*ner 76

您需要使用较低级别的$ .ajax调用或ajaxError函数.这是$ .ajax方法:

function update() {
  $.ajax({
    type: 'GET',
    dataType: 'json',
    url: url,
    timeout: 5000,
    success: function(data, textStatus ){
       alert('request successful');
    },
    fail: function(xhr, textStatus, errorThrown){
       alert('request failed');
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

编辑timeout$.ajax通话中添加了一个并将其设置为五秒钟.


Las*_*ert 9

Dougs答案是正确的,但你实际上可以使用$.getJSON并捕获错误(不必使用$.ajax).只需通过getJSON调用fail函数来链接调用:

$.getJSON('/foo/bar.json')
    .done(function() { alert('request successful'); })
    .fail(function() { alert('request failed'); });
Run Code Online (Sandbox Code Playgroud)

现场演示:http://jsfiddle.net/NLDYf/5/

此行为是jQuery.Deferred接口的一部分.
基本上,它允许您调用该操作后将事件附加到异步操作,这意味着您不必将事件函数传递给操作.

阅读更多关于jQuery.Deferred的信息:http://api.jquery.com/category/deferred-object/