Ajax快速入门

Ajax快速入门

  1. 编写AjaxServlet,并使用response输出字符串
  2. 创建XMLHttpRequest对象:用于和服务器交换数据
  3. 向服务器发送请求
  4. 获取服务器响应数据
//AjaxServlet.java
@WebServlet("/ajaxServlet")
public class AjaxServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 响应数据
        response.getWriter().write("hello ajax~");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
<!--客户端代码-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script>
    // 1. 创建核心对象
    var xhttp;
    if (window.XMLHttpRequest) {
        xhttp = new XMLHttpRequest();
    } else {
        // code for IE6, IE5
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    // 2. 向服务器发送请求
    xhttp.open("GET", "http://localhost:8080/ajax-demo/ajaxServlet", true);
    xhttp.send();
    // 3. 获取服务器的响应数据
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
                alert(this.responseText);
        }
    };

</script>
</body>
</html>