HTML表单:将数据发送到javascript函数
我有一个html页面。它有多种形式 我想要一个通用函数,在提交任何表单后,它将接受该表单的所有输入,并将其作为JSON发送到另一台服务器 据我所知,我想要的是:HTML表单:将数据发送到javascript函数,javascript,php,html,Javascript,Php,Html,我有一个html页面。它有多种形式 我想要一个通用函数,在提交任何表单后,它将接受该表单的所有输入,并将其作为JSON发送到另一台服务器 据我所知,我想要的是: <form enctype="application/json" name="createStudentForm" onsubmit="sendForm()"> Student ID (must be 3 digit number): <input type="text" name="student_i
<form enctype="application/json" name="createStudentForm" onsubmit="sendForm()">
Student ID (must be 3 digit number):
<input type="text" name="student_id"><br>
Nickname:
<input type="text" name="student_nickname"><br>
<input type="submit">
</form>
学生ID(必须是3位数字):
昵称:
后来:
<script>
function sendForm(){
console.log('sent form');
}
</script>
函数sendForm(){
console.log(“已发送表单”);
}
我的问题是:a)为什么我的控制台在我提交时不记录这些内容?当我使用chrome进行测试时,控制台在发送submit后是空的
和b),如何从sendForm()内部访问表单的输入?我是否需要直接引用该表单,或者在调用该表单时是否有方法将数据传递给sendForm()?您可以尝试以下脚本:
$(函数(){
var formHandler=函数(e){
e、 preventDefault();//避免表单提交
var data=$(this.serializeArray();
data=JSON.stringify(data);//到JSON
控制台日志(数据);
};
$('form')。提交(formHandler);
});代码>
表格一
字段1:
字段2:
字段3:
1.
2.
3.
表格二
字段1:
字段2:
字段3:
1.
2.
3.
表格三
字段1:
字段2:
字段3:
1.
2.
3.
根据Michael所说的话,使用一点jquery,您可以非常轻松地完成这项工作
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function sendForm(form){
console.log('sent form: ' + $(form).serialize());
return false;
}
</script>
<body>
<form enctype="application/json" name="createStudentForm" onsubmit="return sendForm(this)">
Student ID (must be 3 digit number):
<input type="text" name="student_id"><br>
Nickname:
<input type="text" name="student_nickname"><br>
<input type="submit">
</form>
</body>
</html>
函数sendForm(form){
log('sent form:'+$(form.serialize());
返回false;
}
学生ID(必须是3位数字):
昵称:
您需要停止表单的实际提交,因为当表单提交时,它将刷新页面并清除控制台。选择在页面刷新时保留控制台日志或添加返回false
tosendForm()
@GeorgeJempty-我听说console.log
的一些实现是异步的,我自己从未体验过。不管怎样,我不认为这与此相关。如果可以,请使用jQuery:https://api.jquery.com/serializeArray/