How to work with json feed stored in localStorage in phonegap application?

That's what I'm doing,

Get a request to my web server, response in json. Using jquery templates to display callback data in my application. Pretty simple, works like a charm.

Here is the problem: I want to save some of this data locally so that my application does not get it from the server every time (3g slower and every transaction hurts my UX ...). So here is what I tried:

$.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'); 

    ...

It fails. (I understand that the code is dumb, just for easy debugging until I work)

If I make it simple

alert(foo);

after capturing 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' 

, , , json localStorage. ? , , json-?

, !

+5
2

JSON :

localStorage.setItem('foo', JSON.stringify(data));

:

JSON.parse(localStorage.getItem('foo'))
+11
App.local = (function () {
  var self = {};

  self.get = function (key) {
    var b = localStorage.getItem(key);
    return b ? JSON.parse(b) : null;
  }

  self.set = function (key, value) {
    var b = JSON.stringify(value);
    localStorage.setItem(key, b);
  }

  return self;
})();

,

var local = App.local;
local.set('foo', 'bar');
var bar = local.get('foo');
console.log(bar);
+4

All Articles