To add some basic error handling, I wanted to rewrite a piece of code that used jQuery's $.getJSON to pull in some photo's from Flickr. The reason for doing this is that $.getJSON doesn't provide error handling or work with timeouts.

Since $.getJSON is just a wrapper around $.ajax I decided to rewrite the thing and surprise surprise, it works flawlessly.

Now the fun starts though. When I deliberately cause a 404 (by changing the URL) or cause the network to timeout (by not being hooked up to the interwebs), the error event doesn't fire, at all. I'm at a loss as to what I'm doing wrong. Help is much appreciated.

以下是代码:

$(document).ready(function(){

    // var jsonFeed = "http://api.flickr.com/services/feeds/photos_public.gne"; // correct URL
    var jsonFeed = "http://api.flickr.com/services/feeds/photos_public.gne_______"; // this should throw a 404

    $.ajax({
        url: jsonFeed,
        data: { "lang" : "en-us",
                "format" : "json",
                "tags" : "sunset"
        },
        dataType: "jsonp",
        jsonp: "jsoncallback",
        timeout: 5000,
        success: function(data, status){
            $.each(data.items, function(i,item){
                $("<img>").attr("src", (item.media.m).replace("_m.","_s."))
                          .attr("alt", item.title)
                          .appendTo("ul#flickr")
                          .wrap("<li><a href=\"" + item.link + "\"></a></li>");
                if (i == 9) return false;
            });
        },
        error: function(XHR, textStatus, errorThrown){
            alert("ERREUR: " + textStatus);
            alert("ERREUR: " + errorThrown);
        }
    });

});

I'd like to add that this question was asked when jQuery was at version 1.4.2

推荐答案

jQuery1.5及更高版本更好地支持JSONP请求的错误处理.但是,您需要使用$.ajax方法,而不是$.getJSON方法.对我来说,这很管用:

var req = $.ajax({
    url : url,
    dataType : "jsonp",
    timeout : 10000
});

req.success(function() {
    console.log('Yes! Success!');
});

req.error(function() {
    console.log('Oh noes!');
});

The timeout seems to do the trick and call the error handler, when there is no successful request after 10 seconds.

我在这个问题上也做了blogpost分.

Jquery相关问答推荐

try 使用jQuery AJAX将参数传递给http Post方法时出现未知错误

使用带有 Ajax GET URL 的数组在每次单击按钮时一次单步执行一个

如何从 onclick div 属性检测 Javascript 中的 control+click?

如何在 jQuery 中 Select 特定的表单元素?

标识符 (id) 是否有通配符 Select 器?

使用 jQuery 更改 CSS 类属性

如何使用 jQuery 以编程方式触发对链接的点击?

如何在循环内创建动态变量名称?

jQuery UI 自动完成宽度未正确设置

如何使用Angular 检测浏览器后退按钮单击事件?

window.onbeforeunload 和 window.onunload 在 Firefox、Safari、Opera 中不起作用?

如何使用 jQuery 显示忙碌指示器?

在 jquery 中启用/禁用下拉框

jquery:更改URL地址而不重定向?

在 JQuery .trigger 上传递参数

C# String.IsNullOrEmpty Javascript 等效项

删除 Javascript 中的所有多个空格并替换为单个空格

jquery更改div类的样式属性

更改 url 而不使用 javascript 重定向

IE 中带有 jQ​​uery ajax 调用的无传输错误