有可能识别/忽略一些拒绝/失败回调吗?
由于jQuery.ajax
api是$.Deferred()
的扩展,我试图用失败和完成的promise模式进行ajax调用。
$.ajax(..).done(..).fail(..)
并使用它来制作某种Api助手。
function ApiHelper() { ... this.get = function (path, data) { return ajax('GET', path, data); }; }
问题:
目前,我需要两种类型的error handling。 一些全球性和一些指定。
如果没有特定的错误,我想由全局失败处理。 否则,由定义的那个。
我想做的事情如下:
apiHelper.get('path/to/api').done(function () { //all good }) function globalHandler() { //everything goes wrong. notify here. } apiHelper.get('path/to/api').done(function () { //all good }).fail(function () { //everything goes wrong., notify here. and ingnore globalHandler. })
有可能确定承诺是否失败,没有人处理它? 或忽略一些失败的回调?
如果没有特定的错误,我想由全局失败处理。 否则,由定义的那个。
注意, .ajaxComplete
, .ajaxError
似乎在 .done
或.fail
之后 .fail
。
尝试为处理的处理错误设置标志; 利用.ajaxComplete
$.ajaxSetup()
var handled = false; $.ajaxSetup({ error: function (jqxhr, textStatus, errorThrown) { console.log("ajaxSetup:", errorThrown); // set , reset `handled` flag here handled = true } }); // returns error var request = $.post("/echo/jsons/", { json: JSON.stringify(["abc"]) }); request.done(function (data) { console.log(data) }); request.fail(function (jqxhr, textStatus, errorThrown) { if (!handled) { console.log("fail:", errorThrown) } else { console.log(handled); } });
jsfiddle http://jsfiddle.net/o8gsdyaj/