Error handling in getJSON calls

后端 未结 9 1643
野的像风
野的像风 2020-11-28 02:09

How can you handle errors in a getJSON call? Im trying to reference a cross-domain script service using jsonp, how do you register an error method?

9条回答
  •  死守一世寂寞
    2020-11-28 02:20

    Here's my addition.

    From http://www.learnjavascript.co.uk/jq/reference/ajax/getjson.html and the official source

    "The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods introduced in jQuery 1.5 are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead."

    I did that and here is Luciano's updated code snippet:

    $.getJSON("example.json", function() {
      alert("success");
    })
    .done(function() { alert('getJSON request succeeded!'); })
    .fail(function() { alert('getJSON request failed! '); })
    .always(function() { alert('getJSON request ended!'); });
    

    And with error description plus showing all json data as a string:

    $.getJSON("example.json", function(data) {
      alert(JSON.stringify(data));
    })
    .done(function() { alert('getJSON request succeeded!'); })
    .fail(function(jqXHR, textStatus, errorThrown) { alert('getJSON request failed! ' + textStatus); })
    .always(function() { alert('getJSON request ended!'); });
    

    If you don't like alerts, substitute them with console.log

    $.getJSON("example.json", function(data) {
      console.log(JSON.stringify(data));
    })
    .done(function() { console.log('getJSON request succeeded!'); })
    .fail(function(jqXHR, textStatus, errorThrown) { console.log('getJSON request failed! ' + textStatus); })
    .always(function() { console.log('getJSON request ended!'); });
    

提交回复
热议问题