本地错误事件之前的全局ajaxError事件

Global ajaxError event before local error event

本文关键字:事件 全局 ajaxError 错误      更新时间:2024-04-17

我有一个全局ajaxError事件,类似于以下内容:

$(document).ajaxError(function myErrorHandler(event, xhr, ajaxOptions, thrownError) {
    alert("There was a global ajax error!");
});

我有很多本地的ajaxEvents,像这样:

$(imageUploadForm).ajaxForm({
            url: assetsUplUrl,
            type: 'POST',
            dataType: 'json',
            data: {project_id: projectId, type: 'image', widget: widget},
            error: function(responseText, status, xhr, form){
                 alert("There was a local ajax error!");
            }
        });     

如何在不更改本地ajax的情况下,在本地错误事件之前触发全局错误事件?

我找到了解决方案。我更改

$(document).ajaxError(function myErrorHandler(event, xhr, ajaxOptions, thrownError) {
    alert("There was a global ajax error!");
});

 $.ajaxSetup({
        error : function(jqXHR, textStatus, errorThrown) {
            alert("There was a global ajax error!");           
            }
    });

和全局处理程序在本地之前调用。

接受的答案对我不起作用。根据https://api.jquery.com/jQuery.ajaxSetup,全局回调函数应该使用它们各自的全局Ajax事件处理程序方法设置,而不是在$.ajaxSetup()options对象中设置。

我的解决方案是使用$.ajaxPrefilter,如下所示:

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
    let error = options.error;
    options.error = function (jqXHR, textStatus, errorThrown) {
        // global error handling first
        console.log('global ajax error');
        
        // override local error handling if exists
        if ($.isFunction(error)) {
            return $.proxy(error, this)(jqXHR, textStatus, errorThrown);
        }
    };
});