简体   繁体   English

了解jQuery的完成/失败/总是在后台

[英]Understanding jquery's done/fail/always under the hood

I know how to use jquery ajax like this. 我知道如何使用像这样的jquery ajax In other words, I understand that .fail gets called on failure etc. 换句话说,我理解.fail会在失败等情况下被调用。

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

I also understand that $.ajax("example.php") returns an object representing a part of the DOM and that there are anonymous functions passed as parameters to done/fail/always. 我也理解$.ajax("example.php")返回表示DOM一部分的对象,并且有匿名函数作为参数传递给done / fail / always。 So far so good. 到现在为止还挺好。 I also get method chaining (or "cascading"): how a function call on an object returns the object, so you can just call the object again with the next method in the chain. 我还获得了方法链接(或“级联”):对对象的函数调用如何返回该对象,因此您可以使用链中的下一个方法再次调用该对象。

However, I am trying to understand how jquery "knows" which of the methods to call from the chain above. 但是,我试图了解jquery如何“知道”从上面的链中调用哪种方法。 It's not like done returns and then fail (the next method in the chain) is called. 这不像完成返回然后失败(调用链中的下一个方法)那样。 So what's going on with this syntax? 那么,这种语法是怎么回事? How does it work under the hood? 它是如何工作的?

Actually, $.ajax() doesn't return object representing a part of DOM, but a promise . 实际上, $.ajax()不会返回表示DOM一部分的对象,而是返回promise

You can read more about promises here . 您可以在此处阅读有关诺言的更多信息。

Quote from the https://api.jquery.com/jQuery.ajax/ 引用https://api.jquery.com/jQuery.ajax/

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). $ .ajax()从jQuery 1.5开始由$ .ajax()返回的jqXHR对象实现Promise接口,为它们提供Promise的所有属性,方法和行为(有关更多信息,请参见Deferred对象)。 These methods take one or more function arguments that are called when the $.ajax() request terminates. 这些方法采用$ .ajax()请求终止时调用的一个或多个函数参数。 This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. 这使您可以在单个请求上分配多个回调,甚至可以在请求完成后分配回调。 (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include: ... (如果请求已经完成,则立即触发回调。)jqXHR对象的可用Promise方法包括:...

Read more at https://api.jquery.com/category/deferred-object/ https://api.jquery.com/category/deferred-object/了解更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM