Catching a JSONP error on a cross-domain request

前端 未结 4 1944
没有蜡笔的小新
没有蜡笔的小新 2021-01-13 00:28

I\'m using jQuery.getJSON() on a URL (different domain) which may not exist. Is there a way for me to catch the error \"Failed to load resource\"? It seems that try/catch do

4条回答
  •  情话喂你
    2021-01-13 00:57

    Deferred objects (new in jQuery 1.5) sound like exactly what you're looking for:

    jQuery.Deferred, introduced in version 1.5, is a chainable utility object that can register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.

    http://api.jquery.com/category/deferred-object/

    EDIT:

    The following code works fine for me:

    function jsonError(){
        $("#test").text("error");
    }
    
    $.getJSON("json.php",function(data){
        $("#test").text(data.a);
    }).fail(jsonError);
    

    json.php looks like this:

    print '{"a":"1"}';
    

    The error function fires for me if the path to json.php is incorrect or if the JSON is malformed. For example:

    print '{xxx"a":"1"}';
    

提交回复
热议问题