Reputation: 197
I am reading one Json file using getJSON() function.
$.getJSON('sample.json', function (data) {
/* but file does not exist in few cases*/
}
How can i check wether file exists or not before processing?
regards
Upvotes: 3
Views: 2168
Reputation: 943601
Do nothing (aside from having a properly configured HTTP server). The function you pass to getJSON
will only get called (and thus only process the data) if you get a successful response.
If the file does not exist on the server you will get a 404
(or 410
) which isn't a successful response, so it won't try to process the data.
getJSON
returns a jqXHR object, so you can also handle the fail condition with different code:
$.getJSON('url')
.done(function (data, textStatus, jqXHR) { /* success */ })
.fail(function (jqXHR, textStatus, errorThrown) { /* error */ });
Upvotes: 5