项目中经常遇到页面提交数据,然而又不想当前页面刷新,这个就需要ajax了。
下面来说说如何简洁的提交一个form表单
1、HTML
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <div > <div class="pull-left"> <form action="${ctx }/ajax/fileUpload" method="post" enctype="multipart/form-data" id="form2"> <input class="btn btn-success btn-sm" type="file" name="uploadFile" id="uploadFile"/> <input type="hidden" name="flag" value="keyword" id="hidden_flag"/> <!-- <button id="submitFile_btn" class="btn btn-success btn-sm" type="submit">添加</button> --> </form> </div> <div class="col-md-4"> <button id="submitFile_btn" class="btn btn-success btn-sm" type="button" onclick="submitFile()">添加</button> </div> </div> </body> </html>
2、js代码
<script type="text/javascript"> function submitFile(){ var form =new FormData(document.getElementById("form2")); openEnable(); //$("#form2").submit(); $.ajax({ url: '${ctx }/ajax/fileUpload', data: form, type: 'post', dataType: 'json', async: true, processData:false, contentType:false, beforeSend: function () { // 禁用按钮防止重复提交 $("#submitFile_btn").text("更新中.."); $("#submitFile_btn").attr({ disabled: "disabled" }); }, success: function (data) { if (data.success == true) { window.location.href = '${ctx }/admin/userList'; } if(data.success == false) { openfailed(); window.location.href = '${ctx }/admin/userList'; } }, complete: function () { $("#submitFile_btn").text("批量添加"); $("#submitFile_btn").removeAttr("disabled"); } }); } </script>
使用
var form =new FormData(document.getElementById("form2"));
减少了js代码中的
var a = $("#a").val();
var b = $("#b").val();
var c = $("#c").val();
var d = $("#d").val();
而且避免了有时会获取不到file文件(个人遇到过,不是绝对)
3、java 后台接受文件
使用:
public @ResponseBody String fileUpload(HttpServletRequest request,HttpServletResponse response,String flag) {
boolean multipart = new CommonsMultipartResolver(request.getSession().getServletContext()).isMultipart(request);
if (multipart) {
MultipartHttpServletRequest multiPartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multiPartRequest.getFile("uploadFile");
InputStream inputStream = file.getInputStream();
}
}
注意:使用MultipartHttpServletRequest 接受文件需要先用红色代码进行判断是否存在,存在之后再强转 HttpServletRequest 为 MultipartHttpServletRequest