使用远程JSON填充HTML5本地存储

时间:2014-08-05 13:47:43

标签: javascript json html5 local-storage

我试图创建一个简单的CRUD手机目录webapp,用户可以从网络服务器(在线时)下载一个小型电话簿(比如公司)到应用程序,然后通过CRUD(包括自己的版本)离线时)。我只是在学习,所以我并不真正感兴趣(在这个阶段)将这些更改同步回服务器。

我发现这个非常有用的教程,介绍如何使用HTML5本地存储和JS来创建CRUD数据库:

http://mrbool.com/creating-a-crud-form-with-html5-local-storage-and-json/26719

但是,如果首先使用从网络服务器下载的JSON数据填充此数据库,我无法工作。

这个想法是用户可以在线时选择他们的公司(比如从下拉列表中选择),然后将电话目录的JSON下载到本地存储数据库,然后可以在本地编辑。

如果有人可以帮我指出正确的方向,我将非常感激。 感谢

2 个答案:

答案 0 :(得分:1)

为了在localStorage或sessionStorage中保存对象,需要将对象转换为字符串。然后当您检索数据时,将其转回对象。

这是我写的两个原型:

Storage.prototype.setObject = function(key, value) {
  this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObject = function(key) {
  var value = this.getItem(key);
  if (value == undefined) return [] ;
  return value && JSON.parse(value);
}

用法:

var obj1 = {a:234, b:456};
localStorage.setObject('obj1', obj1);

console.log(localStorage)    // it's in there


var obj2 = localStorage.getObject('obj1');
console.log(obj2)           // got it back

答案 1 :(得分:1)

看看store.js。它非常简单,它抽象解析JSON或对其进行字符串化。

https://github.com/marcuswestin/store.js/

这是一个示例用法

// Store 'marcus' at 'username'
store.set('username', 'marcus')

// Get 'username'
store.get('username')

// Remove 'username'
store.remove('username')

// Clear all keys
store.clear()

// Store an object literal - store.js uses JSON.stringify under the hood
store.set('user', { name: 'marcus', likes: 'javascript' })

// Get the stored object - store.js uses JSON.parse under the hood
var user = store.get('user')
alert(user.name + ' likes ' + user.likes)

// Get all stored values
store.getAll().user.name == 'marcus'

// Loop over all stored values
store.forEach(function(key, val) {
    console.log(key, '==', val)
})