如何處理AJAX中的錯誤?如何處理jQuery中的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');
}
});
['jQuery.getJSON'(http://api.jquery.com/jQuery.getJSON/)其實上面的代碼減去'錯誤的短手'部分。 –
@SalmanA和'error'部分是必需的。刪除文件將導致一個'404',這將意味着調用'error'函數。在OP的當前代碼中,他沒有'error'處理程序。:沒有任何反應。 –
我不記得說錯誤部分是*不*必需的。 –