来自localstorage jquery的retreive对象

时间:2018-05-24 17:12:47

标签: jquery object local-storage

我正在尝试使用jquery在localstorage中存储一个对象,但似乎无法获得不同的结果:[object Object]。

例如,我如何能够在下面的代码中登录国家?

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
</head> 

<input type="text" id="text"> 
<button value="save" onClick="setStorage()" id="btn"> Save </button>



<script>
function setStorage(){
    var text = $("#text").val();
    testobj = {'country' : 'testcountry', 'population' : 3}
    localStorage.setItem('storage', {'text' : testobj});

    var retreived = localStorage.getItem('storage');
    console.log('retreived : '  + retreived);
}

</script>

1 个答案:

答案 0 :(得分:1)

localStorage存储字符串。出于这个原因,我在将对象等存储到存储时存储JSON,在存储时使用JSON.stringify,在检索时使用JSON.parse

function setStorage(){
    var text = $("#text").val();
    testobj = {'country' : 'testcountry', 'population' : 3}
    localStorage.setItem('storage', JSON.stringify({'text' : testobj}));

    var retreived = JSON.parse(localStorage.getItem('storage'));
    console.log('retreived : '  + retreived);
}