在Javascript和会话存储中对字符串值进行字符串化

时间:2015-10-13 18:01:27

标签: javascript json sessionstorage

我的代码如下:

var employee = {};

employee["fullname"] = document.userForm.fullname.value;
employee["license"] = document.userForm.license.value;
employee["address"] = document.userForm.address.value;
employee["dob"] = document.userForm.dob.value;
employee["city"] = document.userForm.city.value;
employee["state"] = document.userForm.state.value;
employee["zip"] = document.userForm.zip.value;
employee["sex"] = document.userForm.sex.value;

sessionStorage.setItem("session", JSON.stringify({"employees": [employee]}));

以这种方式存储是否正确?如果这是正确的,我如何使用getItem

检索信息

2 个答案:

答案 0 :(得分:1)

使用以下命令检索它:

 var mySessionData = sessionStorage.getItem("session");
 var mySessionDataParsed = JSON.parse( mySessionData );

修改

  

以这种方式存储是否正确

 //sessionStorage.setItem("session", JSON.stringify({"employees": [employee]}));
 sessionStorage.setItem("session", JSON.stringify( employee ) );
 // this way is suffisant ! 
 // but if you prefer an array you can go with your way too !

答案 1 :(得分:0)

您也可以使用点和/或括号表示法。

sessionStorage["session"] = JSON.stringify({"employees": [employee]});
// or
sessionStorage.session = JSON.stringify({"employees": [employee]});

同样适用于作业的右侧。

data = sessionStorage["session"];
// or
data = sessionStorage.session;

无需调用get和set项方法,因为您只需添加不必要的开销。