简体   繁体   中英

Save data to local storage

I'm trying to set a bush of variables in local storage but the function doesn't run, I've tried to get the value but without luck, How can I save fields in Local storage?

function setPerson(){
var person = { 'name': getElementById('name'), 'photo': getElementById('photo')};

// Put the object into the storage
    alert(person);
    localStorage.setItem('person', JSON.stringify(person));
};

HTML In the HTML I'm from fields put values into tags and they are populated, but when I try to fetch them and save them nothing is happening...

I also tried to out fixed values in there and then the alert is displayed, but then it only says object and not the value

var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
alert('retrievedObject: ', JSON.parse(retrievedObject));;

You can use localStorage like this:

// Retrieve your data from locaStorage
var saveData = JSON.parse(localStorage.saveData || null) || {};

// Store your data.
function saveStuff(obj) {
  saveData.obj = obj;
  // saveData.foo = foo;
  saveData.time = new Date().getTime();
  localStorage.saveData = JSON.stringify(saveData);
}

// Do something with your data.
function loadStuff() {
  return saveData.obj || "default";
}

Update 2022:
Since people still view this here's a more modern version. I like to wrap things like this in a service which gives you more control and type safety. You can easily add things like validation and errorhandling.

 class LocalStorageService { #keys = { persons: 'persons', }; constructor() { this.storage = window.localStorage; } addPerson(person) { const persons = this.getPersons(); persons.push(person); this.setPersons(persons); } getPersons() { return JSON.parse(this.storage.getItem(this.#keys.persons)) || []; } getPerson(id) { const persons = this.getPersons(); return persons.find((person) => person.id === id); } setPersons(persons) { this.storage.setItem(this.#keys.persons, JSON.stringify(persons)); } removePerson(person) { const persons = this.getPersons(); const index = persons.indexOf(person); persons.splice(index, 1); this.setPersons(persons); } clear() { this.storage.clear(); } } const storageService = new LocalStorageService(); const person = { id: '1', name: 'John', age: '20', }; storageService.addPerson(person); const persons = storageService.getPersons(); console.log(persons);

Web Storage API - MDN

First, you should use console instead of alert .

And, if you want to use the retrieved object somewhere, you'd better store it in a variable:

var testObject = { 'one': 1, 'two': 2, 'three': 3 };
localStorage.setItem('testObject', JSON.stringify(testObject));
var retrievedObject = JSON.parse(localStorage.getItem('testObject'));
console.log('retrievedObject: ', retrievedObject);

W3C Schools gives you detailed examples on how to work with html and local storage.

w3cSchools - Local Storage

The problem is that getElementById returns an HTML element, which is an object.

Then, JSON.stringify will attempt to iterate its own properties.

But probably, they haven't any (unless you added them manually).

Since you say they are fields, you can try saving its value instead:

var person = {
    name: document.getElementById('name').value,
    photo: document.getElementById('photo').value
};

getElementById should be changed to

    document.getElementById

Also this will get you the entire DOM element. I assume you want what's inside the tag so i would say use

    document.getElementById('name').innerHTML

instead. Just referencing the DOM element will give you a circular strucure error when you attempt to stringify it.

Sample code that i have confirmed works:

<html>
<head>
</head>
<body>
<p id="name">Hello</p>
<p id="photo">photo</p>
<script>

function setPerson(){
var person = { 'name': document.getElementById('name').innerHTML, 'photo':    document.getElementById('photo').innerHTML};

// Put the object into storage
localStorage.setItem('person', JSON.stringify(person));
}
setPerson()
</script>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM