成功()和完成()之间的区别?

从 jQuery 1.5开始,所有 jQuery 的 AJAX 方法都返回一个提供 .error().success().complete()方法的 jqXHR对象。

.success().complete()有什么不同?

83019 次浏览

.success() only gets called if your webserver responds with a 200 OK HTTP header - basically when everything is fine.

However, .complete() will always get called no matter if the ajax call was successful or not - maybe it outputted errors and returned an error - .complete() will still get called.

It's worth mentioning that .complete() will get called after .success() gets called - if it matters to you.

success() is called when the server returns a 200 status code, complete() is called always when the request is complete, no matter the outcome.

success() called when server return 200 status code, complete() is called after success() . and i see some difference :

On success() you can't get xml response string that you get using $.ajax() and set dataType:xml But in complete() you can get string format of readed xml document using

$.ajax({
url:'??',
dataType:'xml',
oncomplete: function(data,status){
console.log(data.responseText);
}
})

success() is called when the server returns success status code, like: 200, 201 etc.

complete() is called always when the request is complete. (no matter, it is success/error response from server.)


So,

  • when there is success response from server: success() and complete() is called.
  • when there is error response from server: error() and complete() is called.

Example: For what purpose you can use complete():
suppose in beforeSend() you show a loader image, and in complete(), you can hide that loader image.