在jquery中,使用ajax提交表单数据。
FormData可以很方便地获取到表单中的所有数据。
注意: ajax中的data参数为FormData类型时,contentType就不要设置成application/json了。
示例如下:
<script type="text/javascript" > ???$(document).ready( function () { ???????$("#commit").click(function () { ???????????var form =new FormData($( "#form-user")[0] ); ????//通过id获取表单的数据 ???????????console.log("ajax"); ???????????$.ajax({ ???????????????type:"POST", ????????????????????????????//请求的类型 ???????????????url:"/user/test", ?????????????????//请求的路径 ???????????????data: form ?, ???????????????????//请求的参数 ???????????????async: false, ???????????????cache: false, ???????????????contentType: false, ???????????????processData: false, ???????????????success: function (msg) { ????????????????//成功返回触发的方法 ???????????????????console.log("ajax请求成功") ???????????????}, ???????????????//请求失败触发的方法 ???????????????error:function(XMLHttpRequest, textStatus, errorThrown){ ???????????????????console.log("ajax请求失败"); ???????????????????console.log("请求对象XMLHttpRequest: "+XMLHttpRequest); ???????????????????console.log("错误类型textStatus: "+textStatus); ???????????????????console.log("异常对象errorThrown: "+errorThrown); ???????????????} ???????????}) ???????}) ???????} ???);</script><body> ???<form ?id="form-user"> ???????账号: ??????<input type="text" name="userName"> ?<br> ???????年龄: ??????????<input type="text" name="age"> ????<br> ???????vip : ????????是: ?<input type="checkbox" name="isVip" value="true"> ????????否: ?<input type="checkbox" name="isVip" value="false"> ??????????<br> ????????生日: ???????<input type="date" name="birthday"> ???????????<br> ??????<button id="commit" >提交</button> ???</form></body>
后台接收数据,如下:
?/** ????* 点击表单,获取formData后通过ajax跳转而来。 ????* @param user ????* @return ????*/ ???@RequestMapping(value = "/user/test",method = RequestMethod.POST ) ???public String getUserInfo( User user ){ ?????????System.out.println(user.getUserName() +","+user.getAge()+","+user.getBirthday()); ????????return "test"; ???}
参考资料 :
https://blog.csdn.net/csdn2193714269/article/details/76269656
https://www.cnblogs.com/zhuxiaojie/p/4783939.html
jquery使用FormData提交数据
原文地址:https://www.cnblogs.com/expiator/p/10041684.html