简体   繁体   English

如何在jquery中处理AJAX中的错误

[英]How can I handle errors in AJAX in jquery

How can I handle errors in AJAX? 如何处理AJAX中的错误?

In my code, the else condition containing console.log is not executed even when the departments.json file is not loaded. 在我的代码中,即使未加载departments.json文件,也不会执行包含console.log的else条件。 I checked it by deleting the departments.json file from where it is loaded into the code. 我通过删除将其加载到代码中的departments.json文件来检查它。

My code is: 我的代码是:

$.getJSON("departments.json?" + new Date().getTime(), {}, function(departments, status, xhr) {
    if (xhr.status == 200) {   
        var numericDepts = [];
        var nonNumericDepts = [];

        for(dept in departments) {   
            $("#kss-spinner").css({'display':'none'});
            if (isNaN(departments[dept].depNo)) {
                if (isNaN(parseInt(departments[dept].depNo,10)))
                    nonNumericDepts[nonNumericDepts.length] = departments[dept];
                else
                    numericDepts[numericDepts.length] = departments[dept];
            }
            else
                numericDepts[numericDepts.length] = departments[dept];
        }

        numericDepts.sort(cmp_dept);
        nonNumericDepts.sort(function(dept1,dept2) {
            return dept1.depNo.toLowerCase() - dept2.depNo.toLowerCase();
        });
        departments.sort(cmp_dept);
        var k = 0;

        $.each(numericDepts.concat(nonNumericDepts), function() {
            if (k % 2 == 0) {
                $('<p class="odd" onClick="selectTag(this,\'' + this.id + '\', 1)">' + this.depNo + '</p>').appendTo($(".scroller", $("#br1")));
            }
            else {
                $('<p class="even" onClick="selectTag(this,\'' + this.id + '\', 1)">' + this.depNo + '</p>').appendTo($(".scroller", $("#br1")));
            }
            k++;
        });
        $("#kss-spinner").css({'display':'none'});
    }
    else {  
        console.log(xhr.status);
        console.log(xhr.response);
        console.log(xhr.responseText)
        console.log(xhr.statusText);
        console.log('json not loaded');
    }
});

You could just use the generic ajax() function: 您可以只使用通用ajax()函数:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: successCallback,
  error: errorCallback
});

You will need to use the fail() method in order to accomplish that. 您将需要使用fail()方法来完成该任务。

Example: 例:

$.get("test.php")
  .done(function(){ alert("$.get succeeded"); })
  .fail(function(){ alert("$.get failed!"); });

if you need a generic error handler use 如果您需要使用通用错误处理程序

  $.ajaxSetup({ 
            error: function(xhr, status, error) {
            // your handling code goes here
            }
            });

JQuery's getJSON function is an abstraction over the regular .ajax() method - but it excludes the error callback. jQuery的getJSON函数是对常规.ajax()方法的抽象-但它不包括错误回调。

Basically, the function you define is only called if the call is successful (that's why it never gets to the else part). 基本上,您定义的函数仅在调用成功时才会调用(这就是为什么它永远不会到达else部分的原因)。

To handle errors, set an error handler before like this: 要处理错误,请像下面这样设置一个错误处理程序:

$.ajaxError(function(event, jqXHR, ajaxSettings, thrownError) { alert("error");});

Whenever an AJAX request completes with an error, the function will be called. 每当AJAX请求完成并出现错误时,都会调用该函数。

You can also append the .error at the end of your getJSON call: 您还可以在getJSON调用结束时附加.error:

$.getJSON("example.json", function() {
    (...)
 }).error(function() { (...) });

The $.getJSON() function is just a special purpose version of the more general .ajax() function. $.getJSON()函数只是更通用的.ajax()函数的特殊用途版本。

.ajax() function will give you the extra functionality you desire (such as an error function). .ajax()函数将为您提供所需的额外功能(例如错误功能)。 You can read more documentation here http://api.jquery.com/jQuery.ajax/ 您可以在这里阅读更多文档http://api.jquery.com/jQuery.ajax/

$.ajax({
  url: "departments.json?" + new Date().getTime(),
  dataType: 'json',
  success: function(departments){
      var numericDepts = [];
      var nonNumericDepts = [];
      for(dept in departments)
      {   
        $("#kss-spinner").css({'display':'none'});
        if(isNaN(departments[dept].depNo))
        {
          if(isNaN(parseInt(departments[dept].depNo,10)))
            nonNumericDepts[nonNumericDepts.length]=departments[dept];
          else
            numericDepts[numericDepts.length]=departments[dept];
        }
        else
          numericDepts[numericDepts.length]=departments[dept];
      }
      numericDepts.sort(cmp_dept);
      nonNumericDepts.sort(function(dept1,dept2) {
        return dept1.depNo.toLowerCase() - dept2.depNo.toLowerCase();
      });
      departments.sort(cmp_dept);
      var k=0;
      $.each(numericDepts.concat(nonNumericDepts),function(){
        if(k%2==0){
          $('<p class="odd" onClick="selectTag(this,\''+this.id+'\',1)">'+this.depNo+'</p>').appendTo($(".scroller",$("#br1")));
        } else {
          $('<p class="even" onClick="selectTag(this,\''+this.id+'\',1)">'+this.depNo+'</p>').appendTo($(".scroller",$("#br1")));
        }
        k++;
      });
      $("#kss-spinner").css({'display':'none'});
  },
  error: function(xhr, textStatus, errorThrown) {  
    console.log(xhr.status);
    console.log(xhr.response);
    console.log(xhr.responseText)
    console.log(xhr.statusText);
    console.log('json not loaded');
  }
});​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM