FormData对象提交表单和form提交表单
FormData
这是HTML5 中新增的API
优点:FormData不仅能读取表单数据,也能自行追加数据
上代码:
js
function fsubmit() { var form=document.getElementById("form1"); var fd =new FormData(form); $.ajax({ url: "server.php", type: "POST", data: fd, processData: false, // 告诉jQuery不要去处理发送的数据 contentType: false, // 告诉jQuery不要去设置Content-Type请求头 success: function(response,status,xhr){ console.log(xhr); var json=$.parseJSON(response); } }); return false; }
html
1 <form name="form1" id="form1"> 2 <p>name:<input type="text" name="name" /></p> 3 <p>gender:<input type="radio" name="gender" value="1" />male <input type="radio" name="gender" value="2" />female</p> 4 <p>stu-number:<input type="text" name="number" /></p> 5 <p>photo:<input type="file" name="photo" id="photo"></p> 6 <p><input type="button" name="b1" value="submit" onclick="fsubmit()" /></p> 7 </form>
Form
js
1 function checkUser(){ 2 var result = document.getElementById("userid").value; 3 var password = document.getElementById("userpassid").value; 4 if(result == "" ){ 5 alert("用户名不能为空"); 6 return false; 7 } 8 if(password == "" ){ 9 alert("密码不能为空"); 10 return false; 11 }else{ 12 return true; 13 } 14 }
html
1 <form id="formid" name="myform" method='post' onsubmit="return checkUser();" > 2 <input type="text" value="" class="text2" name="username" id="userid"/></td> 3 <input type="password" value="" class="text2" name="userpass" id="userpassid"/></td> 4 <input type="submit" value="" class="btn2" /> 5 </form>
方法二
js
1 function checkUser(){ 2 var result = document.getElementById("userid").value; 3 var password = document.getElementById("passid").value; 4 5 if(!result){ 6 alert("用户名不能为空"); 7 return false; 8 } 9 if(!password){ 10 alert("密码不能为空"); 11 return false; 12 } 13 document.getElementById("formid").submit(); 14 }
html
1 <form id="formid" name="myform" method='post'> 2 <input type="text" value="" class="text2" name="username" id="userid"/></td> 3 <input type="password" value="" class="text2" name="userpass" id="userpassid"/></td> 4 <input type="button" value="" class="btn2" onclick="checkUser();" /> 5 </form>
参考出处:
作者:zqifa
出处:http://www.cnblogs.com/zqifa/