Ben*_*Ben 1 javascript ajax jquery
我试图使用jQuery的$ .ajax捕获特定的响应错误.
当存在500或404错误代码时,它运行错误函数而不是运行状态代码函数,我得到一个警告框,而不是应该发生的事情
这是我的代码的样子
// get page data
getPageData: function(url, callback) {
url = ajaxLoader.getURL(url);
$.ajax({
url: url,
type: 'get',
data: {_ajax_loader: 1},
error: function(xhr, status) {
alert('There was a problem loading that page. You may need to refresh.');
},
statusCode: {
404: function(response) {
ajaxLoader.fetchPage('/missing');
},
500: function(response) {
ajaxLoader.fetchPage('/error');
}
}
}).done(callback);
},
Run Code Online (Sandbox Code Playgroud)
这是设计的.error
在服务器返回错误时执行.此外,定义的函数statusCode
也被称为.这同样适用于complete
和success
处理程序.
您可以修改错误处理程序,以便在已定义错误代码时不运行statusCode
.
$.ajax({
url: '/echo',
type: 'get',
success: function() {
console.log('ajax.success');
},
error: function(xhr, status) {
// check if xhr.status is defined in $.ajax.statusCode
// if true, return false to stop this function
if (typeof this.statusCode[xhr.status] != 'undefined') {
return false;
}
// else continue
console.log('ajax.error');
},
statusCode: {
404: function(response) {
console.log('ajax.statusCode: 404');
},
500: function(response) {
console.log('ajax.statusCode: 500');
}
}
});
Run Code Online (Sandbox Code Playgroud)