开发者

how to work with json feed stored in localStorage in phonegap app?

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].n开发者_Go百科ame);

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'))


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;
})();

Now you have a nice interface to local storage,

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜