I have a JSON file my.json with the following content:
{
title: "My Title",
}
And, a jQuery snippet to read it:
var reading_file = $.getJSON('my.json', function (data) {
alert('Success.');
}
The alert() inside the callback never gets called because there is an error in the JSON file i.e. title is not wrapped as a string, as in"title".
When run on the browser (Chrome), this did not throw an error or any indication of something was wrong. To be specific, my.json was retrieved properly (status code: 200), although reading_file.state() is always pending.
My questions:
- What is a good way to catch this type of error i.e. invalid JSON data / syntax?
- Inside the
function (data) { alert ... }callback, what doesthisrefer to?
Thanks.
From the docs
You would use the error handler to catch the error. Something like
Update
As mentioned by Ian,
thisin the success callback context is not an Ajax Event. It appears to be the configuration object passed to$.ajax().