我正在加载JSON数据如下
$.getJSON('data.json', function (data, status, xhr) {
if (status === "success") {
myData= data;
} else {
window.alert("Unexpected error happened. Please refresh your browser window to reload the page. Error: " + xhr + status);
}
});
但是,我通过删除json文件进行了测试。并期待404结果。但是,这并没有显示在alter消息中。在控制台上,它确实为json数据说404。但是,为什么警报框没有显示?
getJSON将调用划分为成功(即HTTP代码200)和错误(即HTTP非200)。发生故障(即非200)时不会调用它。因此,状态在被调用时将始终为“成功”,因为在未调用此回调的情况下,该状态不会被调用。
您应该考虑转换为使用Promise,因为它更加灵活。使用done()方法为接收到200的代码部分注册代码段,为接收到非200的代码注册fail()方法。试试这个:
$.getJSON('someurl').done( function( data ) {
myData = data;
}).fail( function(jqXHR, textStatus, errorThrown) {
console.log("Unexpected error happened. Please refresh your browser window to reload the page. Error: ", textStatus, " ", errorThrown);
});
在编写调试代码时,也请考虑使用console.log而不是alert。您可以在代码中留下console.log()调用,而必须记住删除它们的alert()。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句