jquery.getJSON() error handling
11,104
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
}
})
Author by
Cacheing
Updated on June 19, 2022Comments
-
Cacheing almost 2 years
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
-
Cacheing over 10 yearsi don't get
status == 'parseerror'
, if the returned data is not parseable, the status will beparseerror
? -
Arun P Johny over 10 years@Cacheing yes look at the $.ajax() documentation for
error
callback -
Cacheing over 10 yearsthanks, but it should be handled this way even if the server returned some error by setting
response.setStatus
? -
Arun P Johny over 10 years@Cacheing yes... then the status will be
error
and you can usejqXHR.status
to get the response status like 400/404/403/500 etc... also you can read the response content usingjqXHR.responseText
-
Cacheing over 10 yearsThank you very much. This is very helpful!