ContentServlet.java
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("/content")
public class ContentServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().println("<b>I'm server content</b>");
}
}
index.jsp
<%--
Created by IntelliJ IDEA.
User: 10218
Date: 2019/06/30
Time: 11:33
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>
<input id="btnLoad" type="button" value="加载">
$END$
<div id="divContent"></div>
<script>
document.getElementById("btnLoad").onclick = function () {
// 1. 创建XMLHttpRequest对象
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
}
console.log(xmlhttp);
// 2. 发送Ajax请求
xmlhttp.open("GET","/ajax/content",true)
xmlhttp.send();
// 3. 处理服务器响应
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
var t= xmlhttp.responseText;
alert(t);
document.getElementById("divContent").innerHTML = t;
}
}
}
</script>
</body>
</html>