如何存储在localStorage的在PhoneGap的应用程序JSON饲料工作? [英] how to work with json feed stored in localStorage in phonegap app?

查看:119
本文介绍了如何存储在localStorage的在PhoneGap的应用程序JSON饲料工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我在做什么,

GET请求我的Web服务器,响应是JSON。使用JQuery模板呈现在我的应用程序,回调数据。 pretty的直白,就像一个魅力。

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.

下面的问题:我想存储一些这个数据的本地,这样我的应用程序没有从服务器每次取它(3G是缓慢的,每一笔交易伤害了我的UX ...)。因此,这里是我已经尝试:

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

    ...

这将失败。 (我实现了code是愚蠢的,只是为了方便调试,直到我得到它的工作)

This fails. (I realize the code is silly, just for easy debugging until I get it to work)

如果我做一个简单的

alert(foo);

抓住本地存储的数据后,我看到类似

after grabbing the locally stored data i see something like

[object, Object],[object, Object],[object, Object],...,[object, Object]

如果我这样做

alert(foo[0])

我得到

'['

如果我这样做

alert(foo[0].name);

我得到

'undefined' 

所以,我猜测这是由于数据格式的JSON得到改变,以字符串时,通过的localStorage存储。你同意吗?而且,如果是的话,我能做些什么把它放回JSON格式?

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?

由于一吨!

推荐答案

您需要使用JSON像这样:

You need to use JSON like so:

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

然后分析它:

And then parse it:

JSON.parse(localStorage.getItem('foo'))

这篇关于如何存储在localStorage的在PhoneGap的应用程序JSON饲料工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆