Error handling in getJSON calls

后端 未结 9 1665
野的像风
野的像风 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条回答
  •  旧时难觅i
    2020-11-28 02:26

    $.getJSON() is a kind of abstraction of a regular AJAX call where you would have to tell that you want a JSON encoded response.

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

    You can handle errors in two ways: generically (by configuring your AJAX calls before actually calling them) or specifically (with method chain).

    'generic' would be something like:

    $.ajaxSetup({
          "error":function() { alert("error");  }
    });
    

    And the 'specific' way:

    $.getJSON("example.json", function() {
      alert("success");
    })
    .done(function() { alert("second success"); })
    .fail(function() { alert("error"); })
    .always(function() { alert("complete"); });
    

提交回复
热议问题