jQuery AJAX或XHR请求触发来自完成回调的失败回调 [英] jQuery AJAX or XHR request trigger fail callbacks from done callback

查看:463
本文介绍了jQuery AJAX或XHR请求触发来自完成回调的失败回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我完成的jQuery XHR处理程序(通过$ .get()调用创建)中是否存在一种方法来查找响应中的问题,然后使用自定义触发已注册的后续处理程序(总是失败&总是)错误消息?

Is there a way in my done handler of a jQuery XHR (created from a $.get() call) to look for problems in the response and then trigger the registered subsequent handlers (lie fail & always) with a custom error message?

类似这样的东西:

$.get( URL )
.done(
    function (data, status, res) {
    if(/*some condition*/){
            this.Reject(res, status, "some reason");
            return    
        }
    //Do stuff on success
    }
)

.fail(
//Common error handler here
)
.always(
    //common always handler here
);

完成第二个过滤器的种类.原因当然是所有在200个响应中都出现错误的API,而jQuery永远不会知道这是一个错误.

Kind of a secondary filter on done. The reason is of course all the APIs that shove an error in a 200 response that jQuery could never know was an error.

推荐答案

我想出了如何做到这一点,并且效果很好:

I figured out how to do this, and it works nicely:

$.get( URL )
.then(
    function (data, status, res) {
        if(/**some error check**/({
             return $.Deferred().reject(res, status, "error message");
        }

        return $.Deferred().resolve(data, status, res);
    }
)
.done(
    function (data, status, res) {
        //Do stuff on success
    }
)

.fail(
//Common error handler here
)
.always(
    //common always handler here
);

就像一个魅力一样工作,现在我完成的工作中没有混乱的数据错误处理,我可以专注于处理数据或设置错误消息.

works like a charm, now i don't have messy data error handling in my done, i can just focus on processing data or setting error messages.

这篇关于jQuery AJAX或XHR请求触发来自完成回调的失败回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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