Why does $.getJSON silently fail?

前端 未结 5 1067
闹比i
闹比i 2020-12-02 11:16

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 easies

相关标签:
5条回答
  • 2020-12-02 11:43

    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 thread for details.

    0 讨论(0)
  • 2020-12-02 11:44

    You can use $.ajax instead, and set the dataType options to "json". From the documentation:

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

    0 讨论(0)
  • 2020-12-02 11:48

    Straight from the documentation:

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

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

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

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

    $.ajax({
        url: url,
        dataType: 'json',
        data: data,
        success: callback,
        error: another callback
    });
    
    0 讨论(0)
  • 2020-12-02 12:01

    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

    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
    

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

    0 讨论(0)
  • 2020-12-02 12:02

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

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

    0 讨论(0)
提交回复
热议问题