什么是AJAX: AJAX 是一個架構(architecture)并不是一種技術。AJAX代表異步的JavaScript和XML。
妙語(Punch Line): 延遲加載
問題: 當JavaRSS.com首頁加載時,他同時加載了所有條目的介紹(如果你在設置中激活了)。這些介紹只有當你鼠標移動到該條目的上面的時候才顯示。
現在的問題是用戶不可能是鼠標移過所有的條目,所以預先加載所有的介紹不是個好主意。
解決方案: 使用AJAX,當鼠標移過的時候從服務器動態加載條目的介紹。
這么做可以使初始頁的加載大小減小一半甚至更多,這樣一來頁面加載就更快,就內能得到一個更好的用戶體驗。
時序圖:
我們首先會在onmouseover事件中調用JavaScript函數getDescription。下面是html代碼:
Java & J2EE NewsJava & J2EE News
JavaScript Code:
function getDescription(channelId,itemId) {
var url = 'http://localhost:8080/getDescription.jsp?channelId=' + channelId + '&itemId=' + itemId;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.onreadystatechange = processRequest;
req.open("GET", url, true);
req.send(null);
}
function processRequest() {
if (req.readyState == 4) {
if (req.status == 200) {
parseMessages();
} else {
alert ( "Not able to retrieve description" );
}
}
}
function parseMessages() {
response = req.responseXML.documentElement;
itemDescription = response.getElementsByTagName('description')[0].firstChild.data;
alert ( itemDescription );
}
JSP Code:
資源:
AJAX Java BluePrints Solutions Catalog
AJAX in Wikipedia
W3C HTTP Status Codes
使用AJAX的Google站點:
Gmail
Google Suggest
Google Maps
文章來源于領測軟件測試網 http://www.kjueaiud.com/