Here's what I am doing,
Get request to my web server, response is in json. Using jquery templates to render that callback data in my app. Pretty straightforward, works like a charm.
Here is the problem: I want to store some of this data locally so that my app doesn't have to fetch it from the server every time (3g is slow and every transaction hurts my UX...). So here is what I've attempted:
$.ajax({
url: app_domain + '/pages/home.json',
type: 'get',
datatype: 'json',
data: { mobile: "1" },
async: true,
cache: false,
success: function(data) {
//store locally
localStorage.setItem('foo', data);
//grab from local store
var bar = localStorage.getItem('foo');
// populate template with data
$.tmpl("cityTemplate", bar).appendTo('#all');
...
This fails. (I realize the code is silly, just for easy debugging until I get it to work)
If I do a simple
alert(foo);
after grabbing the locally stored data i see something like
[object, Object],[object, Object],[object, Object],...,[object, Object]
if i do
alert(foo[0])
i get
'['
if i do
alert(foo[0].name);
i get
'undefined'
So, my best guess is this is caused by the data format getting changed from json to string when stored via localStorage. Would you agree? And, if so, what can I do to get it back into json format?
Thanks a ton!
You need to use JSON like so:
localStorage.setItem('foo', JSON.stringify(data));
And then parse it:
JSON.parse(localStorage.getItem('foo'))
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