我想将从HTML表单生成的数据保存到计算机中的JSON文件中,我是该领域的新手。我已在HTML和JavaScript代码下方附上。
<form id="test" action="#" method="post">
<div class="form-group">
<label for="name">Name</label>
<input class="form-control" type="text" name="name" id="name" />
</div>
<div class="form-group">
<label for="check">Check if you like JavaScript</label>
<input type="checkbox" name="check" value="yes" />
</div>
<div class="form-group">
<label for="select">Select your favorite JavaScript framework</label>
<select name="select" class="form-control">
<option value="none" selected="selected">None</option>
<option value="jquery">jQuery</option>
<option value="angularjs">Angular</option>
<option value="mine">Mine, of course!</option>
</select>
</div>
<div class="form-group">
<label for="message">Leave a message</label>
<textarea class="form-control" name="message" rows="15" cols="30"></textarea>
</div>
<div class="form-group">
<label for="email">Email</label>
<input class="form-control" type="text" name="email" id="email" />
</div>
<div class="form-group">
<label for="password">Password</label>
<input class="form-control" type="password" name="password" id="password" />
</div>
<p>
<input type="submit" value="Send" class="btn btn-primary btn-block" />
</p>
(function() {
function toJSONString( form ) {
var obj = {};
var elements = form.querySelectorAll( "input, select, textarea" );
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;
}, false);
});
})();
而不是显示我想将它存储在json文件中的json内容