HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
var xml;
function leehuan() {
var elee = "leehuanhaa"
if (window.XMLHttpRequest) {
xml = new XMLHttpRequest()
} else {
xml = new ActiveXObject("Microsoft.XMLHTTP")
}
if (null != xml)
{
elee = document.getElementById("txt1").innerHTML;
xml.onreadystatechange = changetxt;
xml.open("POST","Ajex",true);//Ajex为Servlet名称
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xml.send("num1="+elee);//注意,在Servlet需要用=来区分key和value
}
}
function changetxt() {
if(xml.readyState==4 && xml.status==200){
document.getElementById("txt1").innerHTML = xml.responseText;
}
}
</script>
</head>
<body>
<div id="txt1">lalallala</div>
<button id="btn" onclick="leehuan()">点击</button>
</body>
</html>
Servlet代码
public class Ajex extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
String num = req.getParameter("num1");
PrintWriter writer = resp.getWriter();
writer.print(num+"==="+"sucess");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}