Ajax案例1-->GET请求

jsp页面--firstajax.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<script type="text/javascript">

//使用function获取XMLHttpRequest对象
function createXMLHttpRequest(){
    try{
        return new XMLHttpRequest();//一般的大众的浏览器
    }catch(e){
        try{
            return new ActiveXObject("Msxml2.XMLHTTP");//IE6
        }catch(e){
            try{
                return new ActiveXObject("Microsoft.XMLHTTP");    //IE5.5及以下
            }catch(e){
                alert("你的浏览器是远古时代的吗?");
            }
        }
    }
};

window.onload= function(){
    
    var btn = document.getElementById("btn");
    btn.onclick = function(){
       //1.得到对象
        var xmlHttp = createXMLHttpRequest();
        //2.打开连接
        xmlHttp.open("GET","<c:url value='/FirstServlet'/>",true);
        //3.发送请求
        xmlHttp.send(null);
        //4.接收服务器响应
        xmlHttp.onreadystatechange = function(){
            if(xmlHttp.readyState ==4 && xmlHttp.status == 200){
                var text =xmlHttp.responseText;
                //完成逻辑
                var h1 = document.getElementById("h1");//获得h1标签
                
                h1.innerHTML = text ;//把服务器响应的信息写到h1标签中
            }
        };
    };        
};

</script>
<%--
1.给一个按钮,以及一个标题
2.点击按钮时向服务器发送一步请求,得到结果
3.把响应结果显示到标题中
--%>

<body>
<button id = "btn">获得服务器端servlet的数据</button>
<h1 id="h1"></h1>
</body>
</html>

Servlet-->FirstServlet.java


package ajax;

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 FirstServlet extends HttpServlet {

    private static final long serialVersionUID = -1866369869941762275L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
         response.getWriter().print("Hello Ajax!!!");
    }
}

图片展示:


原文地址:https://www.cnblogs.com/vmkash/p/5521316.html