jquery.form.js是一個form插件,支持ajax表單提交和ajax上傳。
使用時,需要在代碼中添加如下:
<script src="http://malsup.github.io/jquery.form.js />
這里講一下,使用jquery.form進行ajax表單上傳。
//js示例 function example(){ //定義ajax提交時的url等 var option={ url:"revise", method:"post", contentType:false, success:function(data){ if(data=="1"){ alert("上傳成功!"); $("#ff").resetForm(); //清空表單 }else{ alert("上傳失敗!");} }, };
//調用jquery.form的api ajaxSubmit進行上傳,option為上面所編寫的上傳規定參數 $("#ff").ajaxSubmit(option); //ff為表單id return false; }
使用jquery.form進行ajax表單提交時,如若對提交路徑等有規定,則需要編寫一個option對象,在option中過獎url等進行編寫規定。最后則調用api ajaxSubmit進行表單上傳。
上面為js部分,下面為h5部分
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 8 <title>jquery.form上傳文件</title> 9 </head> 10 <body> 11 <form id="ff"> 12 <input type="text" name="name" /> 13 <input type="text" name="age" /> 14 <input type="file" name="pic" id="pic"accept="image/png, image/jpeg, image/jpg" /> 15 <button type="button" id="submitButton" value="確認" /> 16 </form> 17 18 <script src="http://malsup.github.io/jquery.form.js"></script> 19 <script type="text/javascript"> 20 $("#submitButton").click(function () { //按鈕點擊事件 21 var option={ 22 url:"revise", 23 method:"post", 24 success:function(data){ 25 if(data=="1"){ 26 alert("上傳成功!"); 27 $("#ff").resetForm(); 28 $("#add").html(""); 29 }else{ 30 alert("上傳失敗!");} }, 31 }; 32 $("#ff").ajaxSubmit(option); 33 return false; 34 }); 35 </script> 36 </body> 37 </html>
表單內,需要上傳的各個input標簽必須要添加屬性name,並正確命名。
使用jquery.form.js上傳表單就是這樣。
這是前段時間做項目時,使用常用ajax提交表單信息出錯,查閱過資料后,個人總結出來的使用jquery.form.js的用法。