我如何...使用JavaScript使用JSON.stringify()和JSON.parse() [英] How do I..Use JSON.stringify() and JSON.parse() with JavaScript
本文介绍了我如何...使用JavaScript使用JSON.stringify()和JSON.parse()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试通过JavaScript和JSON存储和检索一个非常基本的对象 - 当我运行下面的代码时,有些内容被放入localstorage中,但是当我单击retrieve时,我只是将[object Object]附加到段落中。有任何想法吗?干杯。
I'm trying to store and retrieve a very basic obect via JavaScript and JSON - when I run the code below, something gets put into localstorage, but when I click retrieve I just get [object Object] appended to the paragraph. Any ideas? Cheers.
<!DOCTYPE HTML>
<html>
<body>
<script>
function storeusername()
{
var person = {};
person.age = 25;
person.firstname = 'Joe';
person.lastname = 'Smith';
localStorage.setItem('persondetails', JSON.stringify(person));
}
function getusername()
{
document.getElementById('username').innerHTML = JSON.parse(localStorage.getItem('persondetails'));
}
</script>
<br/>
Name: <p id="username"></p>
<input type=button value="Store" onclick="storeusername()" />
<input type=button value="Retrieve" onclick="getusername()" />
</body>
</html>
推荐答案
你得到[object Object]的原因是因为JSON.parse
实际上将返回您已序列化的对象,而不是其中一个属性。
例如,如果您希望输出用户名,请使用以下内容:
The reason you're getting [object Object] is becauseJSON.parse
will actually return the object you have serialized, not one of its properties.
For example, if you wish to output the username, use the following:
var person = JSON.parse(localStorage.getItem('persondetails'));
document.getElementById('username').innerHTML = person.firstname + person.lastname; // Or whatever the username is...
这篇关于我如何...使用JavaScript使用JSON.stringify()和JSON.parse()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文