之前介绍了AJAX的get的请求方式与跨域请求,除此之外AJAX还可以进行异步的post请求,在使用post方式的请求时需要设置请求头,如下:
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
如果没有设置请求头信息的话,服务端是接收不到post数据的。
以下示例简单演示如何提交post表单数据:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<script>
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
// 设置请求头信息
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
} else if (typeof XDmainRequest != "undefined") { //兼容IE
xhr = new XDmainRequest();
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
} else {
xhr = null;
}
return xhr;
}
function sendCode() {
var request = createCORSRequest('post', 'send');
if (request) {
request.onload=function () {
if(request.responseText){
// 显示服务端响应的数据
alert(request.responseText);
}else{
alert("服务端没有响应数据!");
}
};
// 发送post表单数据
request.send("phone="+telNumber.value);
}
}
</script>
<body>
<input type="text" name="phone" id="telNumber" placeholder="手机号码" />
<button type="button" onclick="sendCode()">发送</button>
</body>
</html>
服务端代码:
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/send")
public class SendCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
System.out.println("手机号码是:" + httpServletRequest.getParameter("phone"));
httpServletResponse.setContentType("text/html;charset=UTF-8");
PrintWriter printWriter = httpServletResponse.getWriter();
printWriter.print("服务器已收到");
}
}
服务端控制台打印结果:
手机号码是:1234567899
客户端显示响应数据:
通过AJAX上传文件
上面我们演示了使用AJAX提交post表单数据,那么上传文件的请求方式也是post,以下示例演示简单的使用AJAX做一个带有进度条的文件上传。
页面代码:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<script>
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDmainRequest != "undefined") { //兼容IE
xhr = new XDmainRequest();
xhr.open(method, url, true);
} else {
xhr = null;
}
return xhr;
}
function upload() {
// 表单数据对象
var formData = new FormData();
// 多个文件需要进行逐个遍历
for (var i = 0; i < document.getElementById("files").files.length; i++) {
// 将文件数据添加到表单数据中
formData.append("files", document.getElementById("files").files[i]);
}
var request = createCORSRequest('post', 'upload');
if (request) {
request.onload = function () {
if (request.responseText == "1") {
alert("上传成功!");
} else {
alert("上传失败!");
}
};
// 给进度条添加监听事件,这样才有进度条的效果
request.upload.addEventListener("progress", progressChange, false)
// 上传表单数据
request.send(formData);
}
}
// 改变进度条
function progressChange(event) {
progress1.max = event.total; // 数据的总大小
progress1.value = event.loaded; // 当前已上传的大小
}
</script>
<body>
<input type="file" id="files" name="fileUpload" multiple="multiple"/>
<button type="button" name="button" onclick="upload()">上传</button>
<br><br>
<progress id="progress1"></progress>
</body>
</html>
服务端代码:
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
PrintWriter printWriter = httpServletResponse.getWriter();
// 设置临时文件的保存路径
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
diskFileItemFactory.setRepository(new File("D:/"));
// 实例化文件上传对象
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
servletFileUpload.setHeaderEncoding("UTF-8");
// 文件的保存路径
File savePath = new File(this.getServletContext().getRealPath("/uploadDir"));
System.out.println(savePath.getPath());
try {
// 拿出请求数据
List<FileItem> fileItems = servletFileUpload.parseRequest(httpServletRequest);
for (FileItem fileItem : fileItems) {
// 过滤表单字段
if (!fileItem.isFormField()) {
//兼容IE,IE传过来的是路径,需要截取出文件名
String fileName=fileItem.getName();
if (fileName.indexOf("\\") >= 0) {
System.out.println(fileName);
fileName=fileName.substring(fileName.lastIndexOf("\\"),fileName.length());
}
// 写入文件到保存路径中
FileUtils.copyInputStreamToFile(fileItem.getInputStream(), new File(savePath, fileName));
}
}
} catch (FileUploadException e) {
// 上传失败响应0
printWriter.print("0");
e.printStackTrace();
}
// 上传成功响应1
printWriter.print("1");
}
}
运行效果:
本文转自 ZeroOne01 51CTO博客,原文链接:http://blog.51cto.com/zero01/2055546,如需转载请自行联系原作者