jQuery Ajax post 错误回调

我发现网上很多教程都是只有成功的回调参数,而没有错误的回调

一番百度之后找到一篇
$.ajax、$.get和$.post方法成功,完成请求,错误或失败的回调

个人测试了一下,发现 ajax方法回调是成功的,get和post方法错误

其原因在于

官方改名字了

最后操作到官方文档

在The jqXHR Object有写道

As of jQuery 1.5, all of jQuery’s Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or “jqXHR,” returned by $.post() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The jqXHR.done() (for success), jqXHR.fail() (for error), and jqXHR.always() (for completion, whether success or error; added in jQuery 1.6) methods take a function argument that is called when the request terminates. For information about the arguments this function receives, see the jqXHR Object section of the $.ajax() documentation.

The Promise interface also allows jQuery’s Ajax methods, including $.get(), to chain multiple .done(), .fail(), and .always() callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.

示例代码

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.post( "example.php", function() {
  alert( "success" );
})  //本身自带成功
  .done(function() {
    alert( "second success" );
  }) //成功之后完成执行的代码
  .fail(function() {
    alert( "error" );
  }) //失败执行的代码
  .always(function() {
    alert( "finished" );
  }); //无论成功失败都执行的代码

// Perform other work here ...

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

发表评论

电子邮件地址不会被公开。 必填项已用*标注