form表單是在開發中比較基礎也比較常見的問題了,今天就給大家分享一下有關form表單提交的一些小問題.
首先我們來看一下基本的form結構.這里面我直接引用的bootstrap的form表單的框架。
<form class="form-horizontal" id="form1" name="myForm" action="/cgjxx/fwjl_delete_servlet" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">Email</label> <div class="col-sm-10"> <input type="text" name="email" class="form-control" id="inputEmail3" placeholder="phone"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">Password</label> <div class="col-sm-10"> <input type="password" name="password" class="form-control" id="inputPassword3" placeholder="Password"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <div class="checkbox"> <label> <input type="checkbox"> Remember me </label> </div> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <input type="submit" class="btn btn-default" value="提交"> </div> </div> </form>
簡單來說一下form表單提交時候設置的屬性:
name="myForm" /*所代表的表單的名字*/
action="/cgjxx/fwjl_delete_servlet" /*表單提交地址*/
method="post" /*提交方式:(get,post)看需要來更換*/
enctype="multipart/form-data" /*規定在發送表單數據之前如何對其進行編碼。默認是:"application/x-www-form-urlencoded"*/
注意 a:在提交的form表單中如果包括提交文件(包含input='file'),那么enctype就必需設置成:enctype="multipart/form-data",否則會報錯(或者提交失敗).
注意 b:的就是 input 標簽需要設置name=""值否則提交也會報錯(或者提交失敗),因為傳到服務器的時候也是fname=asdf & lname=asdf 類似這種key=val格式的所以不填也會報錯
這樣當點擊submit按鈕的時候表單就會直接提交,但是我們有時候需要做一些驗證功能,直接提交就不能驗證了,好大家往下看:
解決方案一:將type="submit"改成type="button",把所需要寫的驗證功能或者其他功能寫在function formSubmit(){} 這個方法里面就可以了。
<input type="submit" class="btn btn-default" value="提交">
<input type="button" onclick="formSubmit()" class="btn btn-default" value="signin">
解決方案二:在form 里面加上 onsubmit 屬性在提交表單提交時觸發,這樣也可以解決類似提交前驗證等問題。
<form class="form-horizontal" id="form1" name="myForm" action="/cgjxx/fwjl_delete_servlet" method="post" enctype="multipart/form-data">
<form class="form-horizontal" id="form1" name="myForm" action="/cgjxx/fwjl_delete_servlet" method="post" enctype="multipart/form-data" onsubmit="return formSubmit()">
好了分享就到這里,希望可以幫助有需要的朋友,大神路過也請觀看指正!!!.