为什么$ .getJSON会无声地失败?

Dan*_*ton 43 error-handling jquery json silent

$.getJSON当返回的数据不是有效的JSON时,jQuery 无声地失败似乎非常不方便.为什么这是以无声失败实现的?使用更好的失败行为执行getJSON的最简单方法是什么(例如抛出异常console.log(),或者其他什么)?

Mr *_*ubs 85

您可以使用

        function name() {
            $.getJSON("", function(d) {
                alert("success");
            }).done(function(d) {
                alert("done");
            }).fail(function(d) {
                alert("error");
            }).always(function(d) {
                alert("complete");
            });
        }
Run Code Online (Sandbox Code Playgroud)

如果要查看错误原因,请使用完整版本

function name() {
    $.getJSON("", function(d) {
        alert("success");
    }).fail( function(d, textStatus, error) {
        console.error("getJSON failed, status: " + textStatus + ", error: "+error)
    });
}
Run Code Online (Sandbox Code Playgroud)

如果你的JSON格式不正确,你会看到类似的东西

getJSON failed, status: parsererror, error: SyntaxError: JSON Parse error: Unrecognized token '/'
Run Code Online (Sandbox Code Playgroud)

如果网址错误,您会看到类似的内容

getJSON failed, status: error, error: Not Found
Run Code Online (Sandbox Code Playgroud)

如果您尝试从另一个域获取JSON,违反同源策略,则此方法返回空消息.请注意,您可以使用JSONP(具有其限制)或跨源资源共享(CORS)的首选方法来解决同源策略.

  • 这应该是当前接受的答案 (3认同)
  • 请注意,.error已被弃用 - 最好使用.fail代替:http://api.jquery.com/jQuery.ajax/ (3认同)

Håv*_*ard 29

直接来自文档:

重要提示:从jQuery 1.4开始,如果JSON文件包含语法错误,则请求通常会以静默方式失败.

正如文档页面所说,getJSON只是一种简写方法

$.ajax({
    url: url,
    dataType: 'json',
    data: data,
    success: callback
});
Run Code Online (Sandbox Code Playgroud)

要获得失败行为,您可以使用$ .ajax,如下所示:

$.ajax({
    url: url,
    dataType: 'json',
    data: data,
    success: callback,
    error: another callback
});
Run Code Online (Sandbox Code Playgroud)

  • +1简写`$ .getJSON`很方便,但不够灵活,不能真正有用./叹. (3认同)
  • 这个简写对于新的promise语法`$ .getJSON(...).error(function(){...})很有用. (3认同)