AJAX案例一:发送POST请求

时间:2023-09-25 17:32:44
 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<script type="text/javascript">
function createXMLHttpRequest() {
try {
return new XMLHttpRequest();
} catch (e) {
try {
return ActvieXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
return ActvieXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("用的是什么浏览器啊?");
throw e;
}
}
}
}
window.onload = function() {
var btn = document.getElementById("btn");
btn.onclick = function() {
var xmlHttp = createXMLHttpRequest();
//修改为POST请求方式
xmlHttp.open("POST", "<c:url value='/AServlet'/>", true);
//POST请求要设置请求头
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//添加参数
xmlHttp.send("username=张三&password=123");
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var text = xmlHttp.responseText;
var h1 = document.getElementById("h1");
h1.innerHTML = text;
}
};
};
};
</script>
</head>
<body>
<button id="btn">点击这里</button>
<h1 id="h1"></h1>
</body>
</html>
 import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class AServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//处理编码问题,防止乱码
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");//获取请求参数
response.getWriter().print(username+"已注册");
}
}