我试过搜索,但找不到任何有助于回答我问题的内容。我试图将表单数据发送到JSON格式。同时还在执行console.log以查看JSON的输出方式并将设置为服务器。
以下是我的代码。谢谢你的帮助!
<form enctype='application/json' style="text-align: center" method="post" name="form">
<input name="firstname" value="" type="text" class="form-control" placeholder="First Name">  
<input name="lastname" value="" type="text" class="form-control" placeholder="Last Name">  
<input name="email" value="" type="text" class="form-control" placeholder="Email">  
<select name="category" value="" class="form-control">
<option selected disabled value="choose">--Category--</option>
<option value="furniture">Furniture</option>
<option value="books">Books</option>
<option value="music">Music</option>
</select>  
<input name="itemName" value="" type="text" class="form-control" placeholder="Item Name">  
<input name="itemDesc" value="" type="text" class="form-control" placeholder="Item Description">  
<input name="priceInput" value="" type="text" class="form-control" placeholder="Price ($00.00)">  
<div class="modal-footer">
<button name="submit" value="" onclick ="onsubmit()" class="btn btn-default">Submit</button>
</div>
</form>
<script>
var form;
form.onsubmit = function (e) {
//stop regular form submission
e.preventDefault();
//collect the form data
var data = {};
for (var i = 0, ii = form.length; i <ii; ++i) {
var input = form[i];
if (input.name) {
data[input.name] = input.value;
}
}
//construct an HTTP request
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
//send the collected data as JSON
xhr.send(JSON.stringify(data));
console.log(JSON.stringify(data));
xhr.onloadend = function () {
//done
};
};
</script>
答案 0 :(得分:1)
在您的代码中:
var form;
form <-- currently is undefined
form.onsubmit === undefined.onsubmit
您可以在DOM中的元素上使用onsubmit
函数。为此,您需要设置form
变量以引用代码中的<form>
元素。
您可以使用
var form = document.forms['form']
使用&#39;表格&#39;这是因为您的<form>
代码有name="form"
。