jQuery jqXHR-取消链式调用,触发错误链 [英] jQuery jqXHR - cancel chained calls, trigger error chain

查看:114
本文介绍了jQuery jqXHR-取消链式调用,触发错误链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个ajax实用程序来与我的服务器方法进行接口.我想从jQuery.ajax()调用返回的对象中利用jQuery 1.5+延迟方法.情况正在发生.

I am creating a ajax utility for interfacing with my server methods. I would like to leverage jQuery 1.5+ deferred methods from the object returned from the jQuery.ajax() call. The situation is following.

  1. 服务器端方法始终返回JSON对象:

  1. The serverside method always returns a JSON object:

{ success: true|false, data: ... }

客户端实用程序会像这样发起ajax调用

The client-side utility initiates the ajax call like this

var jqxhr = $.ajax({ ... });

问题区域:

jqxhr.success(function(data, textStatus, xhr) {
     if(!data || !data.success) { 
         ???? // abort processing, trigger error
     }
});
return jqxhr; // return to caller so he can attach his own handlers

所以问题是如何取消所有调用方的成功回调附加调用,从而在????提到的位置触发他的错误处理程序?

So the question is how to cancel invocation of all the callers appended success callbacks an trigger his error handler in the place mentioned with ???? ?

文档说延迟函数调用列表是FIFO,所以我的成功处理程序肯定是第一个.

The documentation says the deferred function invocation lists are FIFO, so my success handler is definitely the first one.

推荐答案

(更新: 请注意,当前jQuery Promises与 Promises/A +规范不兼容-更多此答案.)

(UPDATE: Please note that currently jQuery Promises are not compatible with the Promises/A+ specification - more info in this answer.)

在创建AJAX请求的函数中,还可以创建一个延迟对象,并在将其resolve和reject函数绑定到$ .ajax请求的相应回调并使用一些自定义数据验证后,将一个promise返回给调用方.这个:

In your function where you create the AJAX request you can also create a deferred object and return a promise to the caller after binding its resolve and reject functions to the appropriate callbacks of the $.ajax request with some custom data verification, like this:

function makerequest() {

    var deferred = $.Deferred();
    var promise = deferred.promise();

    var jqxhr = $.ajax({
        // ...
    });

    jqxhr.success(function(data, status, xhr) {
        if (!data || !data.success) {
            deferred.reject(jqxhr, 'error');
        } else {
            deferred.resolve(data, status, xhr);
        }
    });

    jqxhr.error(function(jqXHR, status, error) {
        deferred.reject(jqXHR, status, error);
    });

    return promise;
}

现在,任何人都可以像对您的函数的任何承诺一样使用它:

Now anyone will be able to use it like any promise like this to your function:

var request = makerequest();

request.done(successCallback);
request.fail(errorCallback);

甚至只是:

makerequest().then(successCallback, errorCallback);

如果您还添加以下内容:

If you also add this:

    promise.success = promise.done;
    promise.error = promise.fail;

然后,您的调用方将具有(可能更熟悉).success()和.error()的接口,就像纯$ .ajax()调用一样:

then your caller will have (maybe more familiar) interface of .success() and .error() like with pure $.ajax() calls:

var request = makerequest();

request.success(successCallback);
request.error(errorCallback);

(.complete()的实现留给读者练习.)

(The implementation of .complete() is left as an exercise for the reader.)

观看此演示:

  • http://jsfiddle.net/_rsp/r2YnM/
  • http://jsfiddle.net/_rsp/r2YnM/1/ (more verbose)

这是直接从一个正在运行的项目中提取的另一个示例:

Here's another example pulled directly from a working project:

function ajax(url, data) {
    var self = this;
    var deferred = $.Deferred();
    var promise = deferred.promise();

    var jqxhr = $.ajax({
        url: url,
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        type: 'POST'
    }).done(function (msg, status, xhr) {
        if (!msg || msg.Error) {
            self.doError(msg.Error);
            deferred.reject(jqxhr, 'error');
        } else {
            deferred.resolve(msg, status, xhr);
        }
    });

    return promise;
}

这篇关于jQuery jqXHR-取消链式调用,触发错误链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆