I am using jquery.getJSON(), but I don't know how to do error handling. And these are some situations that I need to handle.
1) what if the returned data is null?
2) what if the returned data is not json parseable?
3) what if some error message is returned? For example, the server returned HTTP ERROR
jQuery getJSON() Method The getJSON() method is used to get JSON data using an AJAX HTTP GET request.
getJSON() is equal to $. ajax() with dataType set to "json", which means that if something different than JSON is returned, you end up with a parse error. So you were mostly right about the two being pretty much the same :).
The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.
It is a callback function that executes on the successful server request. It also has three parameters that are data, status, and xhr in which data contains the data returned from the server, status represents the request status like "success", "error", etc., and the xhr contains the XMLHttpRequest object.
Since the $.getJSON()
returns a promise object uou can use the .fail()
promise callback for case 2 and 3... case 1 needs to be handled in the success callback itself
jQuery.getJSON(...).fail(function(jqXHR, status, error){
if(status == 'parseerror'){
//not valid json
} else {
//some other error
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With