前端页面代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>发送ajax POST请求 看如何携带数据</title>
<script type="text/javascript">
window.onload = function () {
document.getElementById("btn").onclick = function () {
//发送ajax POST 请求
//1.创建ajax核心对象
var xhr = new XMLHttpRequest();
//2.注册回调函数
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200) {
document.getElementById("myDiv").innerHTML = xhr.responseText;
}
else {
alert(this.status)
}
}
};
//3.打开通道
xhr.open("POST","/ajax/request3",true);
//4.发送请求
//发送POST请求需要设置请求头的内容类型,下行代码很重要,有了它就能模拟form表单提交POST请求
//还需要注意这行代码的位置必须是放到打开通道的代码之后,放到"打开通道"之前不可以。
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//使用JS代码获取用户填写的信息
var userName = document.getElementById("userName").value;
var password = document.getElementById("pwd").value;
//xhr.send("注意:放在此处的数据就是在请求体中提交的数据,这里的格式需要遵循HTTP协议:name=value&name=value")
xhr.send("username="+ userName +"&password=" + password)
}
}
</script>
</head>
<body bgcolor="#fff8dc">
用户名:<input type="text" id="userName"><br/>
密码:<input type="password" id="pwd"><br/>
<button id="btn">点击按钮发送ajaxPOST请求</button>
<div id="myDiv"></div>
</body>
</html>
服务端代码:
package com.yjg.ajax.servlet;
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("/request3")
public class AjaxRequest3Servlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//解决post请求中文乱码问题
request.setCharacterEncoding("UTF-8");
//接收数据
String username = request.getParameter("username");
String password = request.getParameter("password");
//设置响应内容的类型和字符集
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("用户名:" + username + ";密码:" + password);
}
}
程序运行之后浏览器页面显示效果: