ajax

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 5 <html>
 6 <head>
 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 8 <title>Insert title here</title>
 9 <script>
10     //创建异步对象 该对象用于在后台与服务器交换数据
11     function createXMLHttpRequest(){
12         try{
13             return new XMLHttpRequest();//支持大多数浏览器
14         }catch(e){
15             try {
16                 return new ActiveXObject("Msxml2.XMLHTTP");//支持IE6
17             } catch (e) {
18                 try {
19                     return new ActiveXObject("Microsoft.XMLHTTP");//得到IE5及更早的版本
20                 } catch (e) {
21                     throw e;
22                 }
23             }
24         }
25     }
26     
27     window.onload= function(){//在文档加载完后执行
28         var btn = document.getElementById("btn");
29         btn.onclick = function(){
30             /*
31             ajax的四步操作,得到服务器的响应把响应的结果显示到h1元素中
32             */
33             /*
34             1.得到异步对象 XMLHttpRequest:用于在后台与服务器交换数据
35             */
36             var xmlHttp = createXMLHttpRequest();
37             /*
38             2.打开与服务器的连接
39              *指定请求方式
40              *指定请求的url
41              *指定是否为异步请求
42             */
43             xmlHttp.open("GET","<c:url value='/AServlet' />",true);
44             /*
45             3.发送请求 如果是get则必须参数为null
46             get请求没有请求体,但也要给出null,不然firebox可能不会发送
47             */
48             xmlHttp.send(null);
49             /*
50             4.给异步对象的onreadysatechange:状态变化 事件注册监听
51             当XMLHttpRequest的状态发生发生改变时将触发该事件 我们只需要4
52             */
53             xmlHttp.onreadystatechange = function(){
54                 /*
55                 双重判断:xmlHttp的状态为4(服务器响应结束),以及服务器响应的状态码为200(响应成功)
56                 */
57                 if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
58                     //获取服务器的响应文本
59                     var text = xmlHttp.responseText;
60                     var h = document.getElementById("h");
61                     h.innerHTML = text;
62                 }
63             }
64         }
65     }
66 </script>
67 </head>
68 <body>
69 <button id="btn">点击这里</button>
70 <h1 id="h"></h1>
71 </body>
72 </html>
原文地址:https://www.cnblogs.com/geyaofendou/p/6492079.html