总结一下关于表单提交的几种方式:
一、使用<input type="submit">
直接提交表单
<form id="form1" action="/test" method="post">
<label for="users">用户名:</label>
<input type="text" name="username" id="user"><br>
<label for="psw">密码:</label>
<input type="password" name="password" id="psw">
<br><br>
<input type="submit" value="提交">
</form>
//或者
//给提交按钮input加上点击事件,调用表单的submit()方法
<input type="submit" value="提交" onclick="formSub">
<script type="text/javascript">
function formSub(){
document.getElementById("form1").submit(); //这里一定是表单的id值
}
</script>
注意:每个input标签都要有name属性,form要有action和method。
当然,这里也可以使用button代替input作为提交的按钮:
button的type属性有两个值:button和submit。当不写type属性时,其type的默认值是submit,点击的话也会直接提交数据:
<button type="submit">提交</button>
结论:以上的做法都不会进行表单数据的验证。
二、使用form的onsubmit()方法对表单数据进行 验证后 再提交
<form id="form1" action="/test" method="post" onsubmit="return checkForm()">
<input type="submit" value="提交">
//或者
<button type="submit">提交</button>
<script type="text/javascript">
function checkForm(){
var user= document.getElementById('user').value;
var psw= document.getElementById('psd').value;
if (...) {
//如果验证不通过
return false;
} else {
//验证通过
return true;
}
}
</script>
这里给form元素加上了onsubmit()方法,它会在“提交”按钮点击的时候被触发,该方法一定要有return返回值,如果值为false则不进行提交,如果为true则提交。
三、给<input type='button'>
添加onclick事件,验证通过则调用submit()方法提交
<form id="form1" action="/test" method="post">
<input type="button" value="提交" onclick="checkForm();">
function checkForm(){
var user= document.getElementById('user').value;
var psw= document.getElementById('psd').value;
if(...){
//验证不通过
return false;
}
document.getElementById("form1").submit();
}
四、使用ajax对数据进行 验证后 再提交
<form id="form1" action="/test" method="post">
<input type="submit" value="提交" onclick="login()">
//或者
<button type="button" onclick="login()">提交</button>
<script type="text/javascript">
function login() {
$.ajax({
type: "POST", //提交方式
dataType: "json", //预期服务器返回的数据类型
url: "/users/login" , //目标url
data: $('#form1').serialize(), //提交的数据
success: function (result) {
console.log(result); //打印服务端返回的数据(调试用)
if (result.resultCode == 200) {
alert("成功");
}
;
},
error : function() {
alert("异常!");
}
});
}
</script>
注意:
如果使用button,要先进行数据验证的话,就必须要将type的值设置为”button”,即表示它仅仅是一个按钮,一个按钮。。。
这里提交的数据’data’,使用了serialize()方法将提交的表单值序列化(即a=1&b=2格式),当然你也可以写成:
{
"username":username,
"password":password
}