AJAX引擎工作原理
环境:
IDE:IntelliJ IDEA 2019.2.4 x64
服务器:Tomcat 8.5.60
代码:
JSP
<%--
Created by IntelliJ IDEA.
User: Admini
Date: 2020/12/19
Time: 19:44
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form>
<span>学号:</span><input type="text" id="sno" name="sno"/>
<input type="button" id="btn" value="查询"/>
</form>
<div id="res"></div>
</body>
<script type="text/javascript">
function GetXmlHttpObject() {
var XMLHttp=null;
try{ XMLHttp=new XMLHttpRequest(); }
catch(e){ try{ XMLHttp=new ActiveXObject("Msxml2.XMLHTTP"); }
catch(e){ XMLHttp=new ActiveXObject("Microsoft.XMLHTTP"); }
}
return XMLHttp;
}
function requestFun(){
var XMLHttp=GetXmlHttpObject();
var sno=document.getElementById("sno").value;
var url="${pageContext.request.contextPath}/queryServlet"; //添加动态前缀
var postStr="sno="+sno;
XMLHttp.open("POST",url,true);
XMLHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //设置头信息
XMLHttp.send(postStr); //向服务器发送HTTP请求(内容-参数)
XMLHttp.onreadystatechange=function(){ //定义响应处理函数
// document.getElementById("res").innerText=XMLHttp.responseText;
document.getElementById("res").innerText=this.responseText;
}
}
document.getElementById("btn").onclick=requestFun;
</script>
</html>
servlet
package 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;
@WebServlet(name = "QueryServlet",urlPatterns = {"/queryServlet"})
public class QueryServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String sno=request.getParameter("sno");
String res="hello,"+sno;
System.out.println(sno);
if(sno!=null){
response.getWriter().write(res);
}
else
response.getWriter().write("学号为空");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}