我有一个通用的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 = ('Unknown 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(); }
- });
- }
- });
这是很好,但我想做的是将通用处理程序作为备份,然后在原始ajax调用中处理单个错误。
因此备份处理程序在404上提醒“bar”,我想提醒“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/