首先讓我們先知道一下什么是AJAX(注意這不是荷蘭的甲級足球俱樂部阿甲克斯)。AJAX的全稱是: Asynchronous JavaScript And XML。
JavaRSS.com是一個關(guān)于Java新聞的聚合站點(diǎn),收錄了幾乎全部的關(guān)于Java的網(wǎng)站的新聞,比如TheServerside。這些新聞,除了標(biāo)題之外,還有一些簡單的說明,如果把這些說明一次性的顯示在首頁上,那么時間估計(jì)會相當(dāng)長(因?yàn)槭醉擄@示了大約600條新聞)。JavaRSS.com在首頁上就采用了AJAX技術(shù),通過Lazy Loading來處理:即只有當(dāng)用戶把鼠標(biāo)移到這個新聞標(biāo)題上的時候,才會顯示這個簡單的說明。
JavaRSS.com在他自己的網(wǎng)站上公布了使用AJAX的細(xì)節(jié)。它的關(guān)鍵部分就是以下的代碼:
1
function getDescription(channelId,itemId) {
2
var url = 'http://localhost:8080/getDescription.jsp?channelId=' + channelId + '&itemId=' + itemId;
3
if (window.XMLHttpRequest) {
4
req = new XMLHttpRequest();
5
} else if (window.ActiveXObject) {
6
req = new ActiveXObject("Microsoft.XMLHTTP");
7
}
8
req.onreadystatechange = processRequest;
9
req.open("GET", url, true);
10
req.send(null);
11
}
12
13
function processRequest() {
14
if (req.readyState == 4) {
15
if (req.status == 200) {
16
parseMessages();
17
} else {
18
alert ( "Not able to retrieve description" );
19
}
20
}
21
}
22
23
function parseMessages() {
24
response = req.responseXML.documentElement;
25
itemDescription = response.getElementsByTagName('description')[0].firstChild.data;
26
alert ( itemDescription );
27
}

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

TheServerside上面post了一條評論“AJAX In Action on JavaRSS”,有興趣的可以看看。其實(shí),Google Map, Gmail 都在使用AJAX。