我的代码如下:
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
?
答案 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项方法,因为您只需添加不必要的开销。