竹马君
在AJAX客户端如何做到的异步呢?实际上就是JavaScript的回调函数起的作用提供一个回调JavaScript函数,一旦服务器响应可用,该函数就被执行业务函数:[javascript] function castVote(rank) {
var url = "/ajax-demo/static-article-ranking.html";
var callback = processAjaxResponse;
executeXhr(callback, url);
}需要异步通讯的函数:function executeXhr(callback, url) {
// branch for native XMLHttpRequest object
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = callback;
req.open("GET", url, true);
req.send()(null);
} // branch for IE/Windows ActiveX version
else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = callback;
req.open("GET", url, true);
req.send()();
}
}
}req.onreadystatechange = callbackreq.open("GET", url, true)第一行定义了JavaScript回调函数,一旦响应就绪它就自动执行,而req.open()方法中所指定的“true”标志说明想要异步执行该请求。一旦服务器处理完XmlHttpRequest并返回给浏览器,使用req.onreadystatechange指派所设置的回调方法将被自动调用。