In my html I'm using a Javascript to try to retrieve a saved Json object in the localStorage. I'm using Google Chrome.
First I get the value of the "name" attribute of my Json object that is in the localStorage, via form, and then execute the script that should retrieve this object, saving in a var. However, I have the following error:
Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at buscaConta (principal.html:114)
at HTMLButtonElement.onclick (principal.html:99)
buscaConta @ principal.html:114
onclick @ principal.html:99
This is the excerpt with my form and the script that retrieves the Json object by "name."
div class="formu" id="formularioDeIdent" style="display:none">
<p class="textoForm"> Informe seu nome: </p>
<form>
<div>
<label for="nome"> Nome: </label>
<input type="text" id="nome" />
</div>
<div class="centralizar">
<br><br>
<button class="botaoPequeno" type="button" onClick="buscaConta()">Buscar sua conta</button>
</div>
<br><br>
<div class="centralizar" style="display:none">
<br><br>
<button class="botaoPequeno" type="button" onClick="mudaMenu('formularioDeIdent', 'menu2')">Prosseguir</button>
</div>
</form>
</div>
<script>
function buscaConta(){
var name = document.getElementById('nome');
//O ERRO OCORRE NA LINHA ABAIXO:
console.log(JSON.parse(localStorage[nome.value]).valueOf());
//console.log(oCliente);
}
</script>
The search form and Json saved in the local Storage:
ThecodeIusetosavetheJsonobjectsinthelocalStorage:
<script>varnome=document.getElementById('nome');varagencia=document.getElementById('agencia');varconta=document.getElementById('conta');varobj;document.getElementById("enviarConta").addEventListener('click', function(){
//Monta o objeto que será salvo
obj = {
nome: nome.value,
agencia: agencia.value,
conta: conta.value
};
//Mostra no console o objeto antes de ser salvo no localStorage
console.log(obj.valueOf());
//Salva o objeto no localStorage
localStorage[nome.value] = JSON.stringify(obj);
});
</script>