8

我有以下代码,我正在使用 JSONP 从站点检索 JSON。我想处理 404 bad request 之类的错误代码。以下对我不起作用。

$.getJSON('https://xyz.com/search?jsonp-callback=?', function(data) {

  alert("success");
})
.success(function() { alert("success 2"); })
.error(function() { alert("error occurred "); })
.complete(function() { alert("Done"); });

成功和完整的方法正在工作,但错误方法不起作用。

4

3 回答 3

6

尝试fail代替error(参见Deferred doc)。

于 2013-02-25T10:52:15.053 回答
4
$.getJSON('https://xyz.com/search?jsonp-callback=?', function(data) {
  alert("success");
})
.success(function() { alert("success 2"); })
.error(function(event, jqxhr, exception) {
    if (jqxhr.status == 404) {
              alert("error occurred ");   
    }
})
.complete(function() { alert("Done"); });

上面的代码可以帮助你。

于 2013-02-25T10:56:46.490 回答
1

这个线程有答案:https ://stackoverflow.com/a/14371049/685925

由于您使用的是 JSONP,因此不会调用 jQuery 创建的回调,因此永远不会调用失败回调。这是 JSONP 的正常行为,唉。

于 2013-12-03T12:39:03.953 回答