如何在jqueryajax调用中检测服务器错误



我使用Jquery从url解析json:代码如下:

function fetchdata() {
var statusUrl = '/api/desk/j/';
$.ajax({
url: statusUrl,
dataType: "json",
type: 'post',
success: function(response) {
alert('ok');
},
error: function(xhr, status, error) {
var err = JSON.parse(xhr.responseText);
alert(err.message);
}
});

}

一切都很好,但如果服务器不可访问,我就无法检测到:我试图在error: function中做一些事情,但似乎只有当json有错误时,error中的代码才会被激发

你有什么想法吗?

谢谢!

您需要从jQuerytextStatus响应对象测试statusText。您可以利用浏览器的开发人员控制台来检查此对象。你可以扩展属性和方法供你阅读,无论你想用什么。只需点击console.log((的返回消息,就可以看到这些你不想用于错误检测的属性和方法。

function fetchdata() {
var statusUrl = '/api/desk/j/';
$.ajax({
url: statusUrl,
dataType: "json",
type: 'post',
success: function(response) {
alert('ok');
},
error: function(textStatus) {
console.log(textStatus);
console.log(textStatus.statusText, textStatus.status);
}
});
}
fetchdata();

最新更新