.getJSON vs .ajax错误处理

时间:2013-06-18 13:44:18

标签: javascript jquery ajax error-handling

我正在尝试在外部json无法加载时调用我的错误函数。

这适用于.getJSON,但不适用于.ajax。任何人都可以看看代码,并告诉我,如果我错过了什么?

JS在这里:http://jsfiddle.net/8C7Hb/

$.getJSON( "http://foo.com/bar.json", function() {
    $('#method1_result').html('Success');
}).fail(function() { $('#method1_result').html('Fail'); });

$.ajax({
    url: "http://foo.com/bar.json",
    dataType: "jsonp", 
    success: function(data) {
         $('#method2_result').html('Success'); 
    },
    error: function() {
        $('#method2_result').html('Error');
    }
}).fail(function() { $('#method2_result').html('Fail'); });

谢谢。

2 个答案:

答案 0 :(得分:0)

正如我在评论中已经提到的,.getJSON使用 dataType json。通过在jsonp调用中明确将 dataType 设置为.ajax(),可以强制jQuery假设您将使用填充来检索 true json响应(基本上是指动态脚本标签插入)。

dataType 设置为json也会“正确失败”。

答案 1 :(得分:0)

IIRC,jQuery不会在失败的jsonp调用上调用error(这是.fail绑定的内容)。但是,幸运的是,这是一个常见的问题,并且有一个解决方案:https://github.com/jaubourg/jquery-jsonp