douces 2007-3-14 13:21
关于xmlhttprequest文章
Frameworks, IE and XMLHttp
Frameworks, IE and XMLHttp
So far, I pointed out how we are using our framework to enable compatibility between IE and Firefox. The compatibility layer goes both ways. Firefox has native support for the xml http request object directly off the window object. In IE, this same object is exposed via an ActiveX control.
To resolve these differences, we extend the DOM in IE to establish the standard Firefox compatible way to create the xmlhttp request object. Below is a simple code fragment that should run only in IE:
if (!window.XMLHttpRequest) {
window.XMLHttpRequest = function()
{
var xmlHttp = null;
var ex;
try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP.4.0");} catch (ex)
{
try { xmlHttp = new ActiveXObject("MSXML2.XMLHTTP");} catch (ex)
{
try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");} catch (ex){}
}
}
return xmlHttp;
}
}
Now, whereever we need to use the xmlhttp request object, we merely have to call:
var newRequest = new XMLHttpRequest();
This again demonstrates how a framework enables us to develop pages without the typical browser detection.
We also take this approach to extend the basic support of the document DOM. We have found that access to the document's HTML and HEAD element is often very useful. Today the DOM has a body property for accessing the object representing the BODY element. A natural extension would be to add a html and head property. We extend the document via the framework with the following two simple statements:
document.html = document.getElementsByTagName("HTML")[0];
document.head = document.getElementsByTagName("HEAD")[0];
Now we can use those properties as if they were native to the DOM.
Now combine these with standard patterns (e.g., class definitions via closures) and you start to see how we can greatly simplify our approach to web programming.
UPDATE: Better structured the XMLHttpRequest function.
XMLHTTPRequest
Ajax的一个最大的特点是无需刷新页面便可向服务器传输或读写数据(又称无刷新更新页面),这一特点主要得益于XMLHTTP组件XMLHTTPRequest对象。这样就可以向再发桌面应用程序只同服务器进行数据层面的交换,而不用每次都刷新界面也不用每次将数据处理的工作提交给服务器来做,这样即减轻了服务器的负担又加快了响应速度、缩短了用户等候时间。
最早应用XMLHTTP的是微软,IE(IE5以上)通过允许开发人员在Web页面内部使用XMLHTTP ActiveX组件扩展自身的功能,开发人员可以不用从当前的Web页面导航而直接传输数据到服务器上或者从服务器取数据。这个功能是很重要的,因为它帮助减少了无状态连接的痛苦,它还可以排除下载冗余HTML的需要,从而提高进程的速度。Mozilla(Mozilla1.0以上及NetScape7以上)做出的回应是创建它自己的继承XML代理类:XMLHttpRequest类。Konqueror (和Safari v1.2,同样也是基于KHTML的浏览器)也支持XMLHttpRequest对象,而Opera也将在其v7.6x+以后的版本中支持XMLHttpRequest对象。对于大多数情况,XMLHttpRequest对象和XMLHTTP组件很相似,方法和属性也类似,只是有一小部分属性不支持。
XMLHttpRequest的应用:
XMLHttpRequest对象在JS中的应用
var xmlhttp = new XMLHttpRequest();
微软的XMLHTTP组件在JS中的应用
var xmlhttp = new ActiveXObject(Microsoft.XMLHTTP);
var xmlhttp = new ActiveXObject(Msxml2.XMLHTTP);