我正在尝试将JSON数据加载到sessionStorage中,稍后可以检索,但无法弄清楚!我想我做错了。 是否应该使用其他脚本进行Ajax调用?可以将它放在storeUser函数中吗?
function StoreUser() {
let user = {
'id' : 1 ,
'fisrtName' : 'Alexander',
'lastName' : 'Udose',
'email' : 'XXXXXX@yahoo.com',
'phoneNumber' : '555555555',
'address' : '200 CrestView Church RD',
'creditCard' : '4566XXXXXXXXXX',
'favoriteFoods' : [
'Okazi Soup',
'Egusi Soup',
'Jollof rice'
]
};
let person = JSON.stringify(user);
localStorage.setItem('myPerson', person);
// XHRrequest
let xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
} else {
XHR = new ActiveXObject("Microsoft.XMLHTTP");
};
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
let data = JSON.parse(xhr.responseText);
console.log(data);
}
};
XHR.open('POST','person')
}
答案 0 :(得分:0)
您只需要这些行即可使用localStorage保存和加载序列化对象
localStorage.setItem('myPerson', person); //Saves person to localStorage
person = localStorage.getItem('myPerson'); //Loads person from localStorage
person = JSON.parse(person); //Converts the string back to an object