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?
$.getJSON("example.json", function() {
alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
It is fixed in jQuery 2.x; In jQuery 1.x you will never get an error callback
This is quite an old thread, but it does come up in Google search, so I thought I would add a jQuery 3 answer using promises. This snippet also shows:
The code snippet is:
$.getJSON({
url: "https://myurl.com/api",
headers: { "Authorization": "Bearer " + user.access_token}
}).then().always( function (data, textStatus) {
$("#txtAPIStatus").html(data.status);
$("#txtAPIValue").html(data.responseText);
});
In some cases, you may run into a problem of synchronization with this method.
I wrote the callback call inside a setTimeout
function, and it worked synchronously just fine =)
E.G:
function obterJson(callback) {
jqxhr = $.getJSON(window.location.href + "js/data.json", function(data) {
setTimeout(function(){
callback(data);
},0);
}