總結一下關於表單提交的幾種方式:
一、使用<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
}