Rya*_*P13 16 ajax error-handling jquery
我有一个通用的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(); }
});
}
});
Run Code Online (Sandbox Code Playgroud)
因此,当错误不是403时,会显示一个对话框,其中包含与错误相关的文本.
这很好,但我想做的是将通用处理程序作为备份,然后在原始ajax调用中单独处理每个错误.
因此备份处理程序警告404上的"bar"我想提醒"foo":
error: function(xhr) {
if (xhr.status == 404) {
//window.location.href = $('#logon').attr('href');
alert("foo");
}
}
Run Code Online (Sandbox Code Playgroud)
无论如何我都坚持这样做?我不知道如何阻止备份触发,因为它们似乎都在此刻触发.
Lud*_*der 20
您可以在执行自己的错误处理的ajax函数中将ajax属性"global"设置为false.这应该可以防止全局错误处理.检查:http://api.jquery.com/jQuery.ajax#toptions.
我不认为你可以用jQuery来控制它.在ajax调用期间发生的任何错误都会调用全局ajaxError.但是,在全局回调之前调用"本地"错误回调,因此您可以设置一个告诉全局回调不运行的变量.
例如:
var handledLocally = false;
$('html').ajaxError(function(e, xhr, settings, 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;
}
Run Code Online (Sandbox Code Playgroud)
您可以查看此jsFiddle,其中显示了如何实现此功能(请务必在单击链接之前单击顶部运行):http://jsfiddle.net/e7By8/
小智 5
我认为设置全局变量是一个坏主意,因为你可以同时有多个ajax请求。正如前面提到的,“本地”错误回调在全局回调之前被调用。我的解决方案只是将一些自定义属性附加到 jqXHR 对象,例如HandlingLocally并在本地处理程序中将其设置为 true 并在全局处理程序中检查它。
本地处理:
$.ajax({
//some settings
error:function(jqXHR, textStatus, errorThrown){
//handle and after set
jqXHR.handledLocally = true
}
})
Run Code Online (Sandbox Code Playgroud)
全局处理:
$(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
if (jqXHR.handledLocally)) {
return;
}
//handle global error
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10631 次 |
| 最近记录: |