This is the JSON file that I use:
{
"dat": [
{
"name": "Bill",
"age": 20
}
]
}
This is the actual source (dumbed down to show only the bug) that I use. So feel free to past this into an HTML file and tinker.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<div id="out"></div>
<script type="text/javascript">
/******************
* Global Variables
******************/
var counter = 1; //Used to track users movement
var json;
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObject = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
function load(location, storageName)
{
$.ajax({
url: location,
dataType: "text", //force to handle it as text
success: function(data)
{
localStorage.setObject(storageName, JSON.parse(data));
}
})
};
/****************************
* Pushes any content updates to the user.
****************************/
function populate(Number)
{
$.each(json.dat, (function(key, value)
{
$('#out').html('Name: ' + value.name + '<br> Age: ' + value.age);
}))
}
/********************************
* The main program
********************************/
$(document).ready(function(){
load('work.json', 'jsoncache');
json = localStorage.getObject('jsoncache');
populate(counter);
})
</script>
</body>
</html>
The problem that I am having is that the first time the app is loaded, it throws an error in the console. The second time that you load it (just hit refresh) it works perfectly fine.
I found this problem while changing data and refreshing. If i changed the data and refreshed, the localStorage would load and update the data, but the text displayed on the screen would be the same. Hit refresh again, and the text on screen will show the new data (that was loaded the last time the page was refreshed).
Another thing I have found is that if you run the app without having the localStorage already existing, it throws a different error. Anyone know anything about that?
I am not sure if it is a bug in my code or an issue with the browser. Any thoughts?