最通用的定义为:XmlHttp是一套可以在Javascript、VbScript、Jscript等脚本语言中通过http协议传送或从接收XML及其他数据的一套API。XmlHttp最大的用处是可以更新网页的部分内容而不需要刷新整个页面。
来自MSDN的解释:XmlHttp提供客户端同http服务器通讯的协议。客户端可以通过XmlHttp对象(MSXML2.XMLHTTP.3.0)向 http服务器发送请求并使用微软XML文档对象模型Microsoft® XML Document Object Model (DOM)处理回应。
现在的绝对多数浏览器都增加了对XmlHttp的支持,IE中使用ActiveXObject方式创建XmlHttp对象,其他浏览器如:Firefox、Opera等通过window.XMLHttpRequest来创建xmlhttp对象。

XmlHttp对象参考:

属性:

onreadystatechange* 指定当readyState属性改变时的事件处理句柄。只写
readyState 返回当前请求的状态,只读.
responseBody 将回应信息正文以unsigned byte数组形式返回.只读
responseStream 以Ado Stream对象的形式返回响应信息。只读
responseText 将响应信息作为字符串返回.只读
responseXML 将响应信息格式化为Xml Document对象并返回,只读
status 返回当前请求的http状态码.只读
statusText 返回当前请求的响应行状态,只读
* 表示此属性是W3C文档对象模型的扩展.

方法:

abort 取消当前请求
getAllResponseHeaders 获取响应的所有http头
getResponseHeader 从响应信息中获取指定的http头
open 创建一个新的http请求,并指定此请求的方法、URL以及验证信息(用户名/密码)
send 发送请求到http服务器并接收回应
setRequestHeader 单独指定请求的某个http头
 

事件:



-------------------------
--------------------------
--------------------------

详细说明::


XMLHttpRequest 是 Ajax 的关键技术,然而XMLHttpRequest 并非W3C标准。它目前所完成的大量功能将被过渡到W3C的新项目“DOM Level 3 Load and Save”标准里面。通过XMLHttpReques,web页可以从web 服务器得到反馈和需求而不用重新加载页面。用户将停留在相同的页面,而不会注意到脚本可能在后台需求某页面或是在给服务器发送数据。Google Suggest 就是用XMLHttpRequest对象来建立的一个动态web 接口:当你开始在Google 的搜索框中打字时,一个JS脚本发送字母到一服务器并从服务器返回一列建议。W3C “DOM Level 3 Load and Save”标准包含一些相似的功能,但是这些还不能在任何一浏览器中得到实现。所以就目前,如你需要从浏览器发送HTTP请求,你还是得用到 XMLHttpRequest 对象。Javascript 也是靠XMLHttpRequest 来获取XML的。对于不同的浏览器,创建 XMLHttpRequest 对象的方式有些不一样,IE把XMLHttpRequest实现为一个ActiveX对象,其他浏览器把它实现为一个本地JavaScript对象。经过综合多方的脚本,采用以下脚本基本上能够满足在各种浏览器中创建XMLHttpRequest 的需求。
<script type=”text/javascript”> 
var xmlHttp; 
function creatXMLHttpRequest() { 
if (window.ActiveXObject) { 
xmlHttp =  new ActiveXObject(”Microsoft.XMLHTTP”); 

else  if (window.XMLHttpRequest) { 
xmlHttp =  new XMLHttpRequest(); 

else { 
return

}
其中XMLHttpRequest对象包含了一些方法以及属性,先不管它们,等用到了再看。
Methods(方法)
abort() 
Cancels the current request
取消当前的请求
getAllResponseHeaders() 
Returns the complete set of http headers as a string
以字符串的形式返回完整的HTTP头信息
getResponseHeader(”headername”) 
Returns the value of the specified http header
返回指定的HTTP头信息值
open(”method”,”URL”,async,”uname”,”pswd”) 
Specifies the method, URL, and other optional attributes of a request
为一请求指定发放,URL,和其他的任意属性。
The method parameter can have a value of “GET”, “POST”, or “PUT” (use “GET” when requesting data and use “POST” when sending data (especially if the length of the data is greater than 512 bytes.
方法参数可以是 “GET”, “POST”, 或 “PUT” 中的一个(请求数据使用GET比较多而POST发送数据[特别是长度大于512字节的数据])
The URL parameter may be either a relative or complete URL.
URL可以是绝对路径或是相对的路径。
The async parameter specifies whether the request should be handled asynchronously or not. true means that script processing carries on after the send() method, without waiting for a response. false means that the script waits for a response before continuing script processing
异步参数指明是否应该处理请求。设置成“True”的意思是在send()方法结束后脚本继续执行,而不需要等待服务器的回应。“False”则是脚本必须等待服务器的回应后才能继续执行。
send(content) 
Sends the request
发送请求
setRequestHeader(”label”,”value”) 
Adds a label/value pair to the http header to be sent
Properties属性
onreadystatechange* :
An event handler for an event that fires at every state change, typically a call to a JavaScript function.
这个是个最重要的属性,为每次状态的变化而准备的事件处理,往往用于触发一个JavaScript运行。
readyState :
Returns the state of the object:
返回的状态对象:
  • 0 = uninitialized[初始化]
  • 1 = loading[加载中]
  • 2 = loaded[加载完毕]
  • 3 = interactive[交互]
  • 4 = complete [完毕]
responseText : 
Returns the response as a string
以字符串形式返回
responseXML : 
Returns the response as XML. This property returns an XML document object, which can be examined and parsed using W3C DOM node tree methods and properties
以XML的形式返回,这个属性返回一XML文档对象,可用W3C的DOM点树方法和属性来进行解析和检验。
status : 
Returns the status as a number (e.g. 404 for “Not Found” or 200 for “OK”)
以数字的形式返回状态(比如404是”没有找到“或200是”好的“)
statusText: 
Returns the status as a string (e.g. “Not Found” or “OK”)
以字符串形式返回状态(比如”没有找到“或”好的“)


步骤一:”请求” — 如何发送一个HTTP请求?
发送HTTP请求是关键,我们先总结一下步骤,一共是4步:
1. 获得一个XMLHttpRequest实例,可以通过创建,或者访问已存在的XMLHttpRequest对象实例。
<script type=”text/javascript”> 
         var xmlHttp; 
         function creatXMLHttpRequest() { 
         if (window.ActiveXObject) { 
        xmlHttp =  new ActiveXObject(”Microsoft.XMLHTTP”); 
        } 
         else  if (window.XMLHttpRequest) { 
        xmlHttp =  new XMLHttpRequest(); 
        } 
         else { 
         return
        } 
        }
 2. 接下来要决定当收到服务器的响应后,需要做什么。这需要告诉HTTP请求对象用哪一个JavaScript函数处理这个响应。可以将对象的onreadystatechange属性设置为要使用的JavaScript的函数名。
    xmlHttp.onreadystatechange = handleStateChange;
注意:在函数名后没有括号,也无需传递参数。
3. 在定义了如何处理响应后,就要发送请求了。可以调用HTTP请求类的open()和send()方法, 如:
    xmlHttp.open(”GET”, “simpleResponse.xml”, true);
    xmlHttp.send(null);
关于open()后面的几个参数这里要解释一下了。第一个参数是HTTP请求方式 – GET,POST,HEAD 或任何服务器所支持的您想调用的方式。按照HTTP规范,该参数要大写;否则,某些浏览器(如FireFox ) 可能无法处理请求。第二个参数是请求页面的 URL。由于自身安全特性的限制,该页面不能为第三方域名的页面。同时一定要保证在所有的页面中都使用准确的域名,否则调用 open()会得到“permission denied”的错误提示。一个常见的错误是访问站点时使用domain.tld,而当请求页面时,却使用“www.domain.tld”。第三个参数设置请求是否为异步模式。如果是ture, JavaScript函数将继续执行,而不等待服务器响应。这就是”AJAX”中的”Asynchronous”。
4. 向服务器发送请求。send()方法向指定的目标资源发送请求。send()方法允许一个参数,可以是一个字符串或者一个DOM对象。这个参数会作为请求本身的一部分被传输到目的URL。当send()方法里面包含有参数的时候,要确定open()方法里面的第一个参数是“POST”。如果没有数据要作为请求本身的一部分发送,就使用“null”,正如我们的例子中使用的。


步骤 2 – “收到” — 处理服务器的响应
当发送请求时,要提供指定处理响应的JavaScript函数名,步骤一的第二点我们已经定义了这个函数(handleStateChange)。我们来看看这个函数的功能是什么。首先函数会检查请求的状态,如果状态值是4,就意味着一个完整的服务器响应已经收到了,您将可以处理该响应。
    if (XMLHttp.readyState == 4) {
    // everything is good, the response is received
    } else {
    // still not ready
    }
readyState的取值如下:
  • 0 (未初始化)
  • 1 (正在装载)
  • 2 (装载完毕)
  • 3 (交互中)
  • 4 (完成)
接着,函数会检查HTTP服务器响应的状态值。完整的状态取值可参见 W3C站点,我们着重看值为200(OK)的响应。
if (XMLHttp.status == 200) {
// perfect!
} else {
// there was a problem with the request,
// for example the response may be a 404 (Not Found)
// or 500 (Internal Server Error) response codes
}
在检查完请求的状态值和响应的HTTP状态值后, 您就可以处理从服务器得到的数据了。有两种方式可以得到这些数据:
xmlHttp.responseText – 以文本字符串的方式返回服务器的响应
xmlHttp.responseXML – 以XMLDocument对象方式返回响应。处理XMLDocument对象可以用JavaScript DOM函数
整理一下步骤2的代码,就是处理服务器相应函数(handleStateChange):
function handleStateChange() { 
if(xmlHttp.readyState == 4) { 
if(xmlHttp.status == 200) { 
alert(”The server repilied  with: ” + xmlHttp.responseText); 


}
步骤 3 – “万事俱备” - 简单实例
我们现在将整个过程完整地做一次。
发送一个简单的HTTP请求。我们用JavaScript请求一个XML文件,simpleResponse.xml,文件的文本内容为”Hello from the server!”,然后我们”alert()”simpleResponse.xml文件的内容。
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "<A  href ="http://www.w3.org/TR/html4/strict.dtd" >http://www.w3.org/TR/html4/strict.dtd </A>"> 
< html > 
     < head > 
         < meta  http-equiv ="Content-Type"  content ="text/html; charset=iso-8859-1" > 
         < title >Simple XMLHttpRequest </title> 
         < script  type ="text/javascript" > 
            var xmlHttp; 
            function createXMLHttpRequest(){ 
                if (window.ActiveXObject) { 
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 
                } 
                else    
                    if (window.XMLHttpRequest) { 
                        xmlHttp = new XMLHttpRequest(); 
                    } 
            } 
               
            function startRequest(){ 
                createXMLHttpRequest();//创建XMLHttpRequest 
                xmlHttp.onreadystatechange = handleStateChange; 
                xmlHttp.open("GET", "simpleResponse.xml", true); 
                xmlHttp.send(null); 
            } 
               
            function handleStateChange(){ 
                if (xmlHttp.readyState == 4) { 
                    if (xmlHttp.status == 200) { 
                        alert("The server replied with:" + xmlHttp.responseText); 
                    } 
                } 
            } 
         </script> 
     </head> 
     < body > 
         < form  action ="#" > 
             < input  type ="button"  value ="Start Basic Asynchronous Request"  onclick ="startRequest();" /> 
         </form> 
     </body> 
</html>