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

Javascript 如何在jquery中处理AJAX中的错误,javascript,jquery,Javascript,Jquery,如何处理AJAX中的错误 在我的代码中,即使未加载departments.json文件,也不会执行包含console.log的else条件。我通过删除加载到代码中的departments.json文件来检查它 我的代码是: $.getJSON("departments.json?" + new Date().getTime(), {}, function(departments, status, xhr) { if (xhr.status == 200) { var

如何处理AJAX中的错误

在我的代码中,即使未加载
departments.json
文件,也不会执行包含
console.log
的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');
    }
});
$.getJSON(“departments.json?”+new Date().getTime(),{},函数(departments,status,xhr){
如果(xhr.status==200){
var numericDepts=[];
var非数值部门=[];
(部门内的部门){
$(“#kss微调器”).css({'display':'none'});
if(isNaN(部门[部门].部门编号)){
if(isNaN(parseInt(departments[dept].depNo,10)))
非数字部门[非数字部门长度]=部门[部门];
其他的
数字部门[数字部门长度]=部门[部门];
}
其他的
数字部门[数字部门长度]=部门[部门];
}
数字部门分类(cmp\U部门);
非数值depts.sort(函数(dept1,dept2){
返回dept1.depNo.toLowerCase()-dept2.depNo.toLowerCase();
});
部门分类(cmp\U部门);
var k=0;
$.each(numericDepts.concat(nonNumericDepts),function(){
如果(k%2==0){
$('p class=“odd”onClick=“selectTag(this,\''+this.id+'\',1)>'+this.depNo+'

).appendTo($(“.scroller”,$(“\br1”); } 否则{ $('

“+this.depNo+”

).appendTo($(“.scroller”,$(“\br1”); } k++; }); $(“#kss微调器”).css({'display':'none'}); } 否则{ 控制台日志(xhr.status); console.log(xhr.response); console.log(xhr.responseText) console.log(xhr.statusText); log('json未加载'); } });
您需要使用该方法才能完成此任务

例如:

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

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

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

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

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

JQuery的getJSON函数是对常规.ajax()方法的抽象,但它排除了错误回调

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

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

$.ajaxError(function(event, jqXHR, ajaxSettings, thrownError) { alert("error");});
每当AJAX请求完成并出现错误时,就会调用该函数

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

$.getJSON("example.json", function() {
    (...)
 }).error(function() { (...) });
$.getJSON()
函数只是更通用的
.ajax()
函数的一个专用版本

.ajax()
函数将为您提供所需的额外功能(例如错误函数)。您可以在这里阅读更多文档

$.ajax({
url:“departments.json?”+new Date().getTime(),
数据类型:“json”,
成功:职能(部门){
var numericDepts=[];
var非数值部门=[];
对于(部门中的部门)
{   
$(“#kss微调器”).css({'display':'none'});
if(isNaN(部门[部门].部门编号))
{
if(isNaN(parseInt(departments[dept].depNo,10)))
非数字部门[非数字部门长度]=部门[部门];
其他的
数字部门[数字部门长度]=部门[部门];
}
其他的
数字部门[数字部门长度]=部门[部门];
}
数字部门分类(cmp\U部门);
非数值depts.sort(函数(dept1,dept2){
返回dept1.depNo.toLowerCase()-dept2.depNo.toLowerCase();
});
部门分类(cmp\U部门);
var k=0;
$.each(numericDepts.concat(nonNumericDepts),function(){
如果(k%2==0){
$('p class=“odd”onClick=“selectTag(this,\''+this.id+'\',1)>'+this.depNo+'

).appendTo($(“.scroller”,$(“\br1”); }否则{ $('p class=“偶数”onClick=“selectTag(this,\''+this.id+'\',1)>'+this.depNo+'

).appendTo($(“.scroller”,$(“\br1”); } k++; }); $(“#kss微调器”).css({'display':'none'}); }, 错误:函数(xhr、textStatus、errorshown){ 控制台日志(xhr.status); console.log(xhr.response); console.log(xhr.responseText) console.log(xhr.statusText); log('json未加载'); } });​
实际上是上述代码减去
错误部分的缩写。@SalmanA和
错误部分是必需的。删除该文件将导致
404
,这意味着调用
error
函数。在OPs当前代码中,他没有
错误处理程序。:什么都没有发生。我不记得说过错误部分不是必需的。
$.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');
  }
});​