Ajax(Asynchronous JavaScript + XML)的定义:
- standards-based presentation using XHTML and CSS;
- dynamic display and interaction using the Document Object Model;
- data interchange and manipulation using XML and XSLT;
- asynchronous data retrieval using XMLHttpRequest;
- and JavaScript binding everything together.
具体看这篇:Ajax: A New Approach to Web Applications,通俗点儿解释是这样的:client采用Javascript & XMLHttpRequest发请求到server,server处理这个请求,结果返回的是XML,然后client端采用DOM,解析并显示XML。这样实现了页面的局部刷新,由于返回的XML只包含结果而没显示相关的代码,所以反应速度会很快。
其实这个东西不是什么新技术,只是老外总结了一下,提出个新的buzzword而已。以前有很多这样的应用,我就做过一个用来表示一个公司部门人员的树形组织结构,由于部门或人员都很多,只能局部刷新,动态读入子节点。除了Google maps,Gmail,Flickr那些,我想到的,应该算比较实用的应用:
- 树形组织结构
- 动态显示详细信息(其实最该用的是www.btchina.net 他们现在也是动态load的,但是server返回的结构是html,而非xml)
- 进度条(虽然这在CS上应用很方便,但BS挺麻烦的,用Ajax不错)
- 与外部服务的交互,比如读取天气预报,股票代码,甚至内嵌搜索引擎(日本人的这个多tab的yahoo搜索非常cool!)
我觉得实用的代码:
function getXMLHttpRequest() {
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function myAction(){
var req = getXMLHttpRequest();
req.open("GET","http://localhost/a.jsp", true);
req.onreadystatechange = function () {
document.getElementById("prompt").innerHTML = "Loading ...";
if (req.readyState == 4) {
document.getElementById("prompt").style.display = "none";
var xml = req.responseXML;
var root = xml.documentElement;
if (root) {
//var result = root.getElementsByTagName("a");
}
}
}
req.send(null);
}
关于XMLHttpRequest的详细解释:Using the XML HTTP Request Object
推荐看看这个:libXmlRequest: Simple Ajax JavaScript Wrapper