AJAX POST请求步骤
1.创建AJAX核心对象
2.注册回调函数
3.开启通道
4.设置请求头 //这个步骤是提交数据的时候需要
5.发送请求
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AJAX Post请求</title>
</head>
<body>
<script type="text/javascript">
window.onload = function (){
document.getElementById("mybtn").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").innerText = this.responseText
}else {
alert(this.status)
}
}
}
//3.开启通道
xhr.open("POST","/ajax/ajaxpost",true)
//4.设置请求头
// 设置请求头的内容类型。模拟form表单提交数据。
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")//这个代码是固定的
//5.发送请求
// send函数中的参数就是发送的数据,这个数据在“请求体”当中发送。
var username = document.getElementById("username").value;
var password = document.getElementById("password").value
xhr.send("username="+username+"&password="+password+"")
}
}
</script>
用户名:<input type="text" id="username"><br>
密码:<input type="password" id="password"><br>
<button id="mybtn">ajax_post</button><br>
<div id="mydiv"></div>
</body>
</html>
ajax post后端代码
@WebServlet("/ajaxpost")
public class AjaxPostServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
out.print("username:"+username+"password="+password);
}
}
结果: