I have a function in Javascript:

var a = [];
function SaveDataToLocalStorage(data)
{       
    var receiveddata = JSON.stringify(data);
    a.push(receiveddata);
    alert(a);

    localStorage.setItem('session', a);

}

the data parameter is a JSON Object.

But everytime I click the button it overwrites the data in my localstorage.

Does anybody know how to do this?

推荐答案

要在localStorage中正确存储此信息,您需要执行几个步骤.不过,在我们开始编写代码之前,请注意localStorage(目前)不能保存除字符串之外的任何数据类型.您需要序列化用于存储的数组,然后将其解析回以对其进行修改.

Step 1:

The First code snippet below should only be run if you are not already storing a serialized array in your localStorage session variable.
To ensure your localStorage is setup properly and storing an array, run the following code snippet first:

var a = [];
a.push(JSON.parse(localStorage.getItem('session')));
localStorage.setItem('session', JSON.stringify(a));

The above code should only be run once and only if you are not already storing an array in your localStorage session variable. If you are already doing this skip to step 2.

第二步:

修改你的函数如下:

function SaveDataToLocalStorage(data)
{
    var a = [];
    // Parse the serialized data back into an aray of objects
    a = JSON.parse(localStorage.getItem('session')) || [];
    // Push the new data (whether it be an object or anything else) onto the array
    a.push(data);
    // Alert the array value
    alert(a);  // Should be something like [Object array]
    // Re-serialize the array back into a string and store it in localStorage
    localStorage.setItem('session', JSON.stringify(a));
}

This should take care of the rest for you. When you parse it out, it will become an array of objects.

Hope this helps.

Json相关问答推荐

当有嵌套数组而没有嵌套数组时,展平JSON

删除JSON文件的特定内容

SWIFT中的网络经理

如何在VegaLite中应用Times New Roman,CaliBiri字体

在Golang中从 struct 手动创建JSON对象

给定一个包含两个数组的JSON输入文件,如何使用Jolt将一个数组中的每个元素与另一个数组组合在一起?

如何用JQ打印JSON文件的路径和键值

Ansible - 将文件内容添加到字典中

从包含 JSON 对象序列的文件中获取第一个 JSON 对象

Vega-Lite规范:尽管在规范中提供了数据,但显示空图表

每次在 SoapUI 中发送请求时,将 JSON 响应的子 node 分配给项目变量

Golang 解组行为:字段过多?

JOLT JSON 将值从一对多转换为一对一

将文本转换为 python 列表

如何使用 json.net 将数据表转换为 json 字符串?

验证和格式化 JSON 文件

如何在 Perl 中将简单的哈希转换为 json?

Sequelize - 如何仅返回数据库结果的 JSON 对象?

MVC JsonResult camelCase 序列化

如何遍历 JSON 中的条目?