Ok, so this is just a part of my code, and actually works as it's supposed to.
var jqxhr = $.getJSON( "main.json", function(data) {
return data;
});
var json;
window.onload = function() {
var jsonTxt = jqxhr.responseText;
json = JSON.parse(jsonTxt);
....
}
But every 10th attempt or so i get the following error:
Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at window.onload (profile.js:8)
It's really annoying, because it will leave my page blank. I do think it has something to do with me trying to parse the JSON wrong - or something. I really don't know and I'm looking forward to any kind of answer that could lead me to the fix. Thank you.
That unexpected "u" is the first letter of the string "undefined". It happens because your two asynchronous operations (i.e. loading the JSON and loading the window) are racing to completion, and if the JSON isn't loaded fast enough, the window.onload
method will attempt to parse the JSON string that isn't loaded yet.
A solution is to move the JSON loading inside the onload
even handler. Additionally, the whole point of getJSON
is that it already parses the response for you as a JSON object, so there is no need for JSON.parse()
:
window.onload = function() {
$.getJSON( "main.json", function(json) {
// process the results here
});
}
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