jQuery ajax通用错误处理和逐个案例

前端之家收集整理的这篇文章主要介绍了jQuery ajax通用错误处理和逐个案例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个通用的ajax错误处理程序,如下所示:
  1. $('html').ajaxError(function(e,xhr,settings,exception) {
  2.  
  3. var message = '';
  4.  
  5. if (xhr.status == 0) {
  6. message = 'You are offline!\n Please check your network.';
  7. }
  8. else if (xhr.status == 403) {
  9. window.location.href = $('#logon').attr('href');
  10. }
  11. else if (xhr.status == 404) {
  12. message = 'Requested URL not found.';
  13. }
  14. else if (xhr.status == 500) {
  15.  
  16. message = xhr.responseText;
  17.  
  18. $('#cBoxLoadedContent div.news_article_content').append('<p>' + message + '</p>');
  19.  
  20. try {//Error handling for POST calls
  21. message = JSON.parse(xhr.responseText);
  22. }
  23.  
  24. catch (ex) {//Error handling for GET calls
  25. message = xhr.responseText;
  26. }
  27.  
  28. }
  29. else if (errStatus == 'parsererror') {
  30. message = 'Error.\nParsing JSON Request Failed.';
  31.  
  32. }
  33. else if (errStatus == 'timeout') {
  34. message = 'Request timed out.\nPlease try later';
  35. }
  36. else {
  37. message = ('Unknown Error.\n' + xhr.responseText);
  38. }
  39.  
  40. if (message != '' && xhr.status != 500) {
  41. message = message;
  42. }
  43.  
  44. if (xhr.status != 403) {
  45.  
  46. $('#icis_dashboard').append('<p id="ajax_error_msg" class="offScreen">' + message + '</p>');
  47.  
  48. errorBox({
  49. inline: true,width: 0,href: '#ajax_error_msg',onLoadCall: function() { $('#cBoxLoadedContent').jScrollPaneRemove(); },onCleanupCall: function() { $('#ajax_error_msg').remove(); }
  50. });
  51. }
  52.  
  53. });

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

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

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

  1. error: function(xhr) {
  2. if (xhr.status == 404) {
  3. //window.location.href = $('#logon').attr('href');
  4. alert("foo");
  5. }
  6. }

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

解决方法

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

例如:

  1. var handledLocally = false;
  2.  
  3. $('html').ajaxError(function(e,exception) {
  4. if (!handledLocally){
  5. //run the normal error callback code and the reset handledLocally
  6. }
  7. });
  8.  
  9. error: function(){
  10. //set handledLocally to true to let the global callback it has been taken care of
  11. handledLocally = true;
  12. }

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

猜你在找的jQuery相关文章