jQuery AJAX或XHR请求触发来自完成回调的失败回调

编程入门 行业动态 更新时间:2024-10-24 05:18:18
本文介绍了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请求触发来自完成回调的失败回调

本文发布于:2023-11-25 04:08:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628261.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:回调   jQuery   AJAX   XHR

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!