jQuery when(),错误404

时间:2013-12-23 14:17:16

标签: javascript jquery

我知道有200个HTTP响应时可以使用JQuery:

$.when( $.ajax( "test.aspx" ), $.ajax( "test2.aspx" ) ).done(function( ) {
  alert( 'asd' ); // Alerts "123"
});

但是,如果我得到的不仅仅是200响应,如何使用它?例如。在哪里添加错误回调?

2 个答案:

答案 0 :(得分:2)

jQuery允许您对注释中的错误进行编程:

来自http://api.jquery.com/jQuery.ajax/

var jqxhr = $.ajax( "example.php" )
  .done(function() {
    alert( "success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "complete" );
  });

// Perform other work here ...

// Set another completion function for the request above
jqxhr.always(function() {
  alert( "second complete" );
});

如果您想自己定位状态代码,可以再次从文档中继续关注状态代码。

$.ajax({
  statusCode: {
    404: function() {
      alert( "page not found" );
    }
  }
});

可以根据需要添加状态代码。

答案 1 :(得分:1)

$.when( $.ajax( "test.aspx" ) ).then(function( data, textStatus, jqXHR ) {
  alert( jqXHR.status ); // Alerts 200
});

您需要检查jqXHR.status,然后在那里添加回调。