最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery.getJSON().error() isn't being executed on 404 error - Stack Overflow

programmeradmin2浏览0评论

This is a brief outline of my code:

$.getJSON(json_url, function(data) {
    // application logic
}).error(function() {
    console.log("error");
});

The problem is that when the server returns a 404 error, it does not appear to be handled as there is no console.log() saying error, but there is a GET request failure with a code of 404 (Not Found) showing up in the console.

I am using jQuery 1.9.0.

Is there some simple error I am making?

This is a brief outline of my code:

$.getJSON(json_url, function(data) {
    // application logic
}).error(function() {
    console.log("error");
});

The problem is that when the server returns a 404 error, it does not appear to be handled as there is no console.log() saying error, but there is a GET request failure with a code of 404 (Not Found) showing up in the console.

I am using jQuery 1.9.0.

Is there some simple error I am making?

Share Improve this question asked Jan 17, 2013 at 1:11 ixchiixchi 2,3892 gold badges26 silver badges23 bronze badges 5
  • 1 Try .fail instead of .error... the latter is deprecated (though that does not mean that it won't work). – Felix Kling Commented Jan 17, 2013 at 1:19
  • That also does not seem to work. Is there another method to try instead of getJSON for JSONP? Also, the jQuery docs say error on the getJSON page, why would that work, but not what the docs say work? – ixchi Commented Jan 17, 2013 at 1:24
  • Are you sure it's a 404 and not a JSON syntax error, which will fail silently? – Beetroot-Beetroot Commented Jan 17, 2013 at 1:35
  • It's JSONP, would that make a difference? With the callback function it's not valid JSON, but without it it's valid. I'm calling the Twitter API, if that makes a difference. – ixchi Commented Jan 17, 2013 at 1:37
  • 1 As I understand, Twitter will respond with JSONP if a callback="..." function is present. Similarly, jQuery will handle the request as JSONP if callback="..." is present. I think the problem with a 404 is that servers can return HTML (a page containing a marked up error message). This question asks the same question - you may be able to glean something from the answers (though unfortunately none is accepted). – Beetroot-Beetroot Commented Jan 17, 2013 at 2:05
Add a ment  | 

1 Answer 1

Reset to default 3

Due to the nature of JSONP requests, the error callback is not called for those.

From the docs:

When data is retrieved from remote servers (which is only possible using the script or jsonp data types), the error callbacks and global events will never be fired.

发布评论

评论列表(0)

  1. 暂无评论