jQuery   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了jQuery ajax通用错误处理和逐个案例大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个通用的ajax错误处理程序,如下所示:
$('html').ajaxError(function(e,xhr,setTings,exception) {

    var message = '';

    if (xhr.status == 0) {
        message = 'You are offline!\n Please check your network.';
    }
    else if (xhr.status == 403) {
        window.LOCATIOn.href = $('#logon').attr('href');
    }
    else if (xhr.status == 404) {
        message = 'requested URL not found.';
    }
    else if (xhr.status == 500) {

        message = xhr.responseText;

        $('#cBoxLoadedContent div.news_article_content').append('<p>' + message + '</p>');

        try {//Error handling for POST calls
            message = JSON.parse(xhr.responseText);
        }

        catch (eX) {//Error handling for get calls
            message = xhr.responseText;
        }

    }
    else if (errStatus == 'parsererror') {
        message = 'Error.\nParsing JSON request Failed.';

    }
    else if (errStatus == 'timeout') {
        message = 'request timed out.\nPlease try later';
    }
    else {
        message = ('Unk@L_874_8@n Error.\n' + xhr.responseText);
    }

    if (message != '' && xhr.status != 500) {
        message = message;
    }

    if (xhr.status != 403) {

        $('#icis_dashboard').append('<p id="ajax_error_msg" class="offScreen">' + message + '</p>');

        errorBox({
            inline: true,width: 0,href: '#ajax_error_msg',onLoadCall: function() { $('#cBoxLoadedContent').jScrollPaneRemove(); },onCleanupCall: function() { $('#ajax_error_msg').remove(); }
        });
    }

});

所以当错误不是403时,显示一个错误有关的文本的对话框。

这是很好,但我想做的是将通用处理程序作为备份,然后在原始ajax调用中处理单个错误

因此备份处理程序在404上提醒“bar”,我想提醒“foo”:

error: function(xhr) {
            if (xhr.status == 404) {
                //window.LOCATIOn.href = $('#logon').attr('href');
                alert("foo");    
            }
        }

我反正这样做吗?我现在不知道如何防止备份被触发。

解决方法

我不认为你可以用jQuery控制这个。在ajax调用期间发生的任何错误调用全局ajaxError。但是,“本地”错误回调在全局回调之前被调用,所以您可以设置一个变量来告诉全局回调不运行。

例如:

var handledLocally = false;

$('html').ajaxError(function(e,exception) {
    if (!handledLocally){
        //run the normal error callBACk code and the reset handledLocally
    }
});

error: function(){
    //set handledLocally to true to let the global callBACk it has been taken care of
    handledLocally = true;
}

您可以查看这个jsfiddle显示如何完成(请确保单击链接之前单击顶部的运行):http://jsfiddle.net/e7By8/

大佬总结

以上是大佬教程为你收集整理的jQuery ajax通用错误处理和逐个案例全部内容,希望文章能够帮你解决jQuery ajax通用错误处理和逐个案例所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。