Why does $.getJSON silently fail?

前端 未结 5 1089
闹比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: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
    });
    

提交回复
热议问题