2

如何处理 AJAX 中的错误?

console.log在我的代码中,即使departments.json没有加载文件,也不会执行包含的 else 条件。我通过删除departments.json加载到代码中的文件来检查它。

我的代码是:

$.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');
    }
});
4

5 回答 5

4

您可以只使用通用ajax()函数:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: successCallback,
  error: errorCallback
});
于 2012-11-29T12:50:12.703 回答
1

如果您需要通用错误处理程序,请使用

  $.ajaxSetup({ 
            error: function(xhr, status, error) {
            // your handling code goes here
            }
            });
于 2012-11-29T12:50:41.507 回答
1

JQuery 的 getJSON 函数是对常规.ajax()方法的抽象——但它不包括错误回调。

基本上,只有在调用成功时才会调用您定义的函数(这就是它永远不会到达 else 部分的原因)。

要处理错误,请在之前设置一个错误处理程序,如下所示:

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

每当 AJAX 请求完成并出现错误时,都会调用该函数。

您还可以在getJSON调用末尾附加 .error :

$.getJSON("example.json", function() {
    (...)
 }).error(function() { (...) });
于 2012-11-29T12:51:03.390 回答
1

您将需要使用fail()方法来完成此操作。

例子:

$.get("test.php")
  .done(function(){ alert("$.get succeeded"); })
  .fail(function(){ alert("$.get failed!"); });
于 2012-11-29T12:47:16.783 回答
0

$.getJSON()函数只是更通用.ajax()函数的特殊用途版本。

.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');
  }
});​
于 2012-11-29T12:57:41.493 回答