1
<input type="button" onclick="ajaxTest()" value="AJAX測試">
2
3
<input type="button" onclick=" document.getElementById('weather').innerHTML='' " value="隱藏">
4
5
<script>
6
// 1. 初始化 請求 對象
7
// Mozilla/Firefox 下的
8
var xmlhttp = new XMLHttpRequest();
9
// IE 下的
10
//var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
11
//alert(xmlhttp);
12
13
function ajaxTest() {
14
// 指定要打開的頁面
15
xmlhttp.open("GET", "staticpage.html", true);// HTTP 請求的方式, URL, 是否異步
16
// 指定頁面打開完之后要進行的操作.
17
xmlhttp.onreadystatechange = mychange;
18
// 開始發起瀏覽請求, Mozilla 必須加 null
19
xmlhttp.send(null);
20
}
21
22
// 這個函數就是每次狀態改變要調用的函數
23
function mychange() {
24
// 請求已完成
25
if(xmlhttp.readyState == 4) {
26
//alert(xmlhttp.readyState);
27
alert(xmlhttp.responseText);
28
// 更新對應的 HTML 元素里面顯示的內容
29
// 根據 ID 引用頁面里面的元素 document.getElementById(元素名)
30
document.getElementById('weather').innerHTML = xmlhttp.responseText;
31
}
32
}
33
</script>
34
35
<div id="weather"></div>

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35
