为什么$ .getJSON默默地失败? [英] Why does $.getJSON silently fail?

查看:404
本文介绍了为什么$ .getJSON默默地失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery的 $。getJSON 似乎非常不方便当返回的数据无效JSON时,将静默失败。为什么这样实现了无声的失败?什么是最好的方法来执行getJSON更好的失败行为(例如抛出一个异常, console.log()或其他)?

It seems very inconvenient that jQuery's $.getJSON silently fails when the data returned is not valid JSON. Why was this implemented with silent failure? What is the easiest way to perform getJSON with better failure behavior (e.g. throw an exception, console.log(), or whatever)?

推荐答案

可以使用

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

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

If you want to see the cause of the error, use the full version

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

如果您的JSON格式不正确,您会看到像



If your JSON is not well-formed, you will see something like

getJSON failed, status: parsererror, error: SyntaxError: JSON Parse error: Unrecognized token '/'

如果网址错误,您会看到类似于

If the URL is wrong, you will see something like

getJSON failed, status: error, error: Not Found

如果您正在尝试要从另一个域中获取JSON,违反同源策略,此方法返回一条空白信息。请注意,您可以使用JSONP(具有限制)或相同原因的跨原始资源共享的首选方法( CORS )。

If you are trying to get JSON from another domain, violating the Same-origin policy, this approach returns an empty message. Note that you can work around the Same-origin policy by using JSONP (which has it's limitations) or the preferred method of Cross-origin Resource Sharing (CORS).

这篇关于为什么$ .getJSON默默地失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆