AJAX in Action


像其他人一样,当我看到一下RIA应用,例如Google Maps和Google Suggest的时候我都非常惊讶。我希望知道是如何实现的。现在,谜底揭开了,那就是AJAX。这是在我花了一段时间研究AJAX之后才知晓的。这里有一个很好的例子让我们知道AJAX是如何很好的应用在 JavaRSS.com 里面的。

什么是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

本文作者:
« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3