JQuery 移动 JSON 字符串化

JQuery Mobile JSON Stringify

我是 jquery 手机新手。我正在为我的学校作业做一个购物清单应用程序,我被要求将对象存储在本地存储中。

每件商品必须包含以下信息:商品名称、商品数量和布尔值 is_bought。 我希望将所有项目数据存储到一个 JSON 字符串中。项目数据由用户从其他页面输入。

我的问题是 1)如何通过 JSON stringify.

将项目存储在本地存储中

2)如何从 JSON 字符串中检索项目数据以表示为列表。

首先:如果我没理解错的话,你的对象(json)结构如下:

{
  "name": "cheese",
  "quantity": 2,
  "is_bought": false
}

如果不是(有问题的是您的变量没有键(名称)),您的结构 必须 就像我展示的那样可以访问对象中的每个变量。

第二:关于localStorage。它仅限于处理字符串 key/value 对,所以你不能只在其中保存一个对象。您必须使用 JSON.stringify() 将您的对象解析为字符串并保存在 localStorage 中,然后,在检索后,使用 JSON.parse() 将其解析回来。代码可能如下所示:

var item = {"name": "cheese", "quantity": 2, "is_bought": true};

// Store item into localStorage
localStorage.setItem('item', JSON.stringify(item));
// Retrieve item from localStorage
var retrievedItem = localStorage.getItem('item');
var parsedItem = JSON.parse(retrievedItem);

编辑:存储多个项目

因此,如果您的问题是关于存储多个项目并区分它们,并且 如果您的项目名称是 unique 并且您知道什么商品已购买,您可以使用商品名称的键将它们存储到本地存储中,例如

// You can do this in a for loop
localStorage.setItem('item_' + item.name, JSON.stringify(item));

// And to change (if you already know bought item's name), 'cheese' for example
var retrievedItem = localStorage.getItem('item_cheese'); 
var parsedItem = JSON.parse(retrievedItem);
parsedItem.is_bought = true;
// And save again in localStorage
localStorage.setItem('item_cheese', JSON.stringify(parsedItem));