将对象数组设置为sessionStorage [英] Setting an array of objects to sessionStorage

查看:181
本文介绍了将对象数组设置为sessionStorage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好,所以我有这个JSON:

Ok, so I have this JSON:

{"Status":"OK!","ListaPermessi":
[{"IdPermesso":10,"Nome":"WIND_PARAMS"},
 {"IdPermesso":11,"Nome":"ADMIN_SERVER"},
 {"IdPermesso":21,"Nome":"REC"},
 {"IdPermesso":22,"Nome":"REC_DIST"},
 {"IdPermesso":23,"Nome":"REC_DIST_CR"}
]}

我的代码是:

var parsedResult = JSON.parse(result); // where result is the above JSON
if (parsedResult.Status === "OK!") {
    // Set sessionStorage vars
    if (typeof(Storage) !== "undefined") {
        // localStorage & sessionStorage support!

        sessionStorage.setItem("ListaPermessi", parsedResult.ListaPermessi);
    }
    else {
        // Sorry! No web storage support :(
    }
}

但是...这不能正常工作!分配后,从Firebug中看到的sessionStorage看起来像这样:

But... this is not working properly! After the assignment, the sessionStorage seen from Firebug looks like this:

sessionStorage :

  • ListaPermessi =" [对象对象],[对象对象],[对象对象],[对象对象],[对象对象] "

通过JavaScript将对象数组分配给 sessionStorage 变量的正确方法是什么?

What is the proper way to assign an array of objects to a sessionStorage variable from javascript?

推荐答案

您需要将其转换回JSON字符串.您可以使用 JSON.stringify 方法:

You need to turn it back into a JSON string. You can do that with the JSON.stringify method:

sessionStorage.setItem("ListaPermessi", JSON.stringify(parsedResult.ListaPermessi));

这样做的原因是Web存储只能存储字符串,并且默认的toString方法Object返回,如您现在所见,为"[object Object]".

The reason for this is that web storage can only store strings, and the default toString method of Object returns, as you've now seen, "[object Object]".

旁注: typeof 是运算符,而不是函数,因此不需要括号:

Side note: typeof is an operator, not a function, so there's no need for the parentheses:

if (typeof Storage !== "undefined") { //...

这篇关于将对象数组设置为sessionStorage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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