简体   繁体   English

检查函数是否是jQuery ajax请求

[英]Check if function is jQuery ajax request

I am writing an ajax queue and I want to ensure that the type of function (comes in an object) is in fact an ajax request so that .done/.fail/.always can be called on it. 我正在写一个ajax队列,我想确保函数类型(在一个对象中)实际上是一个ajax请求,以便可以在其上调用.done / .fail / .always。 How can I do this? 我怎样才能做到这一点?

I want to ensure that the type of function (comes in an object) is in fact an ajax request so that .done/.fail/.always can be called on it. 我想确保函数类型(来自对象)实际上是一个ajax请求,以便可以在其上调用.done / .fail / .always。

jQuery ajax request objects ( jqXHR ) aren't functions. jQuery ajax请求对象( jqXHR )不是函数。 In jQuery v1.12.0 (the version I had handy to check), they're plain objects with properties added (eg, no special constructor), so you can't use instanceof to see if they're jqXHR objects. 在jQuery v1.12.0(我方便检查的版本)中,它们是添加了属性的普通对象(例如,没有特殊的构造函数),所以你不能使用instanceof来查看它们是否是jqXHR对象。

You can test whether done , fail , and/or always are present on the object you get: 您可以测试donefail和/或always存在于您获得的对象上:

if (obj.done && obj.fail && obj.always) {
    // It's probably a jqXHR
}

Or if you wanted to be more thorough you might make sure they were functions: 或者如果你想要更彻底,你可以确保它们是功能:

if (typeof obj.done == "function" &&
    typeof obj.fail == "function" &&
    typeof obj.always == "function") {
    // It's probably a jqXHR
}

This is an example of "duck typing": It quacks like a duck, so we'll assume it's a duck. 这是“鸭子打字”的一个例子:它像鸭子一样嘎嘎叫,所以我们假设它是一只鸭子。

If you want to really limit it as much as you can to jqXHR objects and not other things that have those functions, you could check for other functions/properties that they have, such as getAllResponseHeaders and such. 如果你想尽可能多地限制它到jqXHR对象而不是其他具有这些功能的东西,你可以检查它们拥有的其他功能/属性,例如getAllResponseHeaders等。

I've used this before: 我之前用过这个:

if(data && $.isFunction(data.promise)) {
...
}

I want to ensure that the type of function (comes in an object) is in fact an ajax request so that .done/.fail/.always can be called on it. 我想确保函数类型(来自对象)实际上是一个ajax请求,以便可以在其上调用.done / .fail / .always。

From the jQuery.ajax() documentation: 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). 自jQuery 1.5起,$ .ajax()返回的jqXHR对象实现了Promise接口,为它们提供了Promise的所有属性,方法和行为(有关更多信息,请参阅Deferred对象)。

Available Promise methods of the jqXHR object include: jqXHR对象的可用Promise方法包括:

jqXHR.done(function( data, textStatus, jqXHR ) {}); jqXHR.done(function(data,textStatus,jqXHR){}); An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. 成功回调选项的替代构造,.done()方法替换了不推荐使用的jqXHR.success()方法。 Refer to deferred.done() for implementation details. 有关实现的详细信息,请参阅deferred.done()。

jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {}); jqXHR.fail(function(jqXHR,textStatus,errorThrown){}); An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. 作为错误回调选项的替代构造,.fail()方法替换了不推荐使用的.error()方法。 Refer to deferred.fail() for implementation details. 有关实现的详细信息,请参阅deferred.fail()。

jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { });* An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method. jqXHR.always(function(data | jqXHR,textStatus,jqXHR | errorThrown){}); *完整回调选项的替代构造,.always()方法替换了不推荐使用的.complete()方法。

Related question/answers: 相关问题/答案:

  1. Any way to check whether a variable is a real jqXHR? 有什么方法可以检查变量是否是真正的jqXHR?
  2. How can I tell if an object is a jQuery Promise/Deferred? 如何判断对象是否为jQuery Promise / Deferred?

Checking if something is a promise, or in jQuery's case a Deferred, can be done by checking that the object is "thenable" , ie that it has a then() method 检查某些东西是否是一个承诺,或者在jQuery的情况下是一个Deferred,可以通过检查该对象是可以”来完成,即它有一个then()方法

var xhr = $.ajax({url:'...'});

if (typeof xhr === 'object' && typeof xhr.then === 'function') ...

This would work with any promises (also A+), to specifically check for the fail , done and always methods that a jQuery ajax call always would have, see TJ's answer. 这将适用于任何promises(也是A +),专门检查jQuery ajax调用总是会有faildonealways方法,请参阅TJ的答案。

Try checking for status property, calling .state() function 尝试检查status属性,调用.state()函数

if (object.status && (obj.state() === "resolved" || obj.state() === "rejected")) {
      if (obj.status === 200) obj.done(success)
      else obj.fail(err)
} else {
  // do other stuff
}

alternatively, use .ajaxComplete() , which should be called at completed $.ajax() requests 或者,使用.ajaxComplete() ,它应该在完成的$.ajax()请求中调用

All ajaxComplete handlers are invoked, regardless of what Ajax request was completed. 无论Ajax请求完成了什么,都会调用所有ajaxComplete处理程序。 If you must differentiate between the requests, use the parameters passed to the handler. 如果必须区分请求,请使用传递给处理程序的参数。 Each time an ajaxComplete handler is executed, it is passed the event object, the XMLHttpRequest object, and the settings object that was used in the creation of the request. 每次执行ajaxComplete处理程序时,都会传递事件对象, XMLHttpRequest对象以及在创建请求时使用的设置对象。

$(document).on("ajaxComplete", function(event, xhr, settings) {
   // do stuff
})

Old question but I think all those answers are pretty unsatisfying. 老问题,但我认为所有这些答案都非常不满意。 If someone in the future really wants to check if a passed object is a Promise try this function. 如果将来有人真的想检查传递的对象是否是Promise,请尝试此函数。

function isPromise (obj) {
    const normal = !!obj && typeof obj === 'object' &&
                   ((obj.constructor && obj.constructor.name === 'Promise') || typeof obj.then === 'function');

    const fnForm = !!obj  && (typeof obj === 'function') && 
                   ((obj.name === 'Promise') || (typeof obj.resolve === 'function') && (typeof obj.reject === 'function'));

    return normal || fnForm;
}

works with ES6 promises, Bluebird and jQuery ajax. 适用于ES6承诺,Bluebird和jQuery ajax。

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

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