代码之家  ›  专栏  ›  技术社区  ›  Patrick Oscity

jQuery:处理失败AJAX请求的回退

  •  36
  • Patrick Oscity  · 技术社区  · 16 年前

    jQuery能否为失败的AJAX调用提供回退?这是我的尝试:

    function update() {
        var requestOK = false;
    
        $.getJSON(url, function(){
            alert('request successful');
            requestOK = true;
        });
    
        if (!requestOK) {
            alert('request failed');
        }
    }
    

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

    5 回复  |  直到 16 年前
        1
  •  85
  •   Julian Camilleri    8 年前

    $.ajax 打电话,或者 ajaxError

    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');
        }
      });
    }
    

    编辑 timeout $.ajax 呼叫并将其设置为5秒。

        2
  •  12
  •   Lasse Skindstad Ebert    13 年前

    Dougs的答案是正确的,但实际上您可以使用 $.getJSON 并捕获错误(不必使用 $.ajax getJSON 打电话给警察局 fail 功能:

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

    http://jsfiddle.net/NLDYf/5/

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

    http://api.jquery.com/category/deferred-object/

        3
  •  2
  •   Jonathon Faust    16 年前
        4
  •  2
  •   thebaron24    8 年前

    var promise = $.ajax({
        type: 'GET',
        dataType: 'json',
        url: url,
        timeout: 5000
      }).then(function( data, textStatus, jqXHR ) {
        alert('request successful');
      }, function( jqXHR, textStatus, errorThrown ) {
        alert('request failed');
    });
    
    //also access the success and fail using variable
    promise.then(successFunction, failFunction);
    
        5
  •  1
  •   Sean Vieira    16 年前

    我相信您正在寻找jquery的错误选项 ajax object

    getJSON是 $.ajax 对象,但它不提供对错误选项的访问权限。

    编辑:

    推荐文章