嗨,我正在尝试学习json,我是一个总的支持者,我会非常感激任何建议。谢谢。
我有一个json文件名file1.json,下面有一些内容
{
"name": "Example object",
"lastname": "asdfgh"
}
{
"name": "Example object2",
"lastname": "asdfgh2wer"
}
然后我有html,每次单击提交按钮时,我都需要输入我想要的名称和姓氏,所输入的数据将存储在 file1.json我的代码在名称“ Form1.html”下,但未向json文件添加任何内容
<style type="text/css">
body {
margin: 2em auto;
max-width: 600px;
}
form div {
margin-bottom: 0.5em;
}
form div label, form div input {
display: block;
margin-bottom: 0.3em;
}
</style>
<form id="test" action="#" method="post">
<div class="form-group">
<label for="name">First Name</label>
<input class="form-control" type="text" name="name" id="name" />
<label for="name">Last Name</label>
<input class="form-control" type="text" name="lastname" id="lastname" />
</div>
<input type="submit" value="Send" class="btn btn-primary btn-block" />
</p>
</form>
<pre id="output"></pre>
<script type="text/javascript">
(function() {
function toJSONString( form ) {
var obj = {};
var elements = form.querySelectorAll( "input");
for( var i = 0; i < elements.length; ++i ) {
var element = elements[i];
var name = element.name;
var value = element.value;
if( name ) {
obj[ name ] = value;
}
}
return JSON.stringify( obj );
}
document.addEventListener( "DOMContentLoaded", function() {
var form = document.getElementById( "test" );
var output = document.getElementById( "output" );
form.addEventListener( "submit", function( e ) {
e.preventDefault();
var json = toJSONString( this );
output.innerHTML = json;
localStorage.setItem('user.json', JSON.stringify(json));
}, false);
});
})();
</script>