jQuery 为什么 $.getJSON 会默默地失败?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5492838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:15:23  来源:igfitidea点击:

Why does $.getJSON silently fail?

jqueryjsonerror-handlingsilent

提问by Dan Burton

It seems very inconvenient that jQuery's $.getJSONsilently 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)?

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

回答by Mr Shoubs

you can use

您可以使用

        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)
    });
}

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

如果您的 JSON 格式不正确,您将看到类似

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

If the URL is wrong, you will see something like

如果 URL 错误,您将看到类似

getJSON failed, status: error, error: Not Found

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).

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

回答by H?vard

Straight from the documentation:

直接来自文档:

Important:As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently.

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

As the documentation page says, getJSON is simply a shorthand method for

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

$.ajax({
    url: url,
    dataType: 'json',
    data: data,
    success: callback
});

To get failure behavior, you can use $.ajax like this:

要获得失败行为,您可以像这样使用 $.ajax:

$.ajax({
    url: url,
    dataType: 'json',
    data: data,
    success: callback,
    error: another callback
});

回答by karim79

You can use $.ajaxinstead, and set the dataTypeoptions to "json". From the documentation:

您可以$.ajax改用,并将dataType选项设置为“json”。从文档:

"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)

“json”:将响应评估为 JSON 并返回一个 JavaScript 对象。在 jQuery 1.4 中,JSON 数据以严格的方式解析;任何格式错误的JSON 都会被拒绝并抛出解析错误。(有关正确 JSON 格式的更多信息,请参阅 json.org。)

回答by CrazyDart

You should have a look at the docs for this API... it has a .error on it.

你应该看看这个 API 的文档......它有一个 .error 。

http://api.jquery.com/jQuery.getJSON/

http://api.jquery.com/jQuery.getJSON/

回答by b.squared

If you're requesting JSONP as the response, you will get a silent fail if there is no response (e.g. network outage). See this threadfor details.

如果您请求 JSONP 作为响应,那么如果没有响应(例如网络中断),您将获得无提示失败。有关详细信息,请参阅此线程