XMLHttpRequest的同步和异步请求

类别:.NET开发 点击:0 评论:0 推荐:

客户端利用XMLHTTP发送请求得到服务端应答数据,并用Javascript操作DOM最终更新页面- 又称无刷新更新页面,有代替传统web开发中采用form(表单)递交方式更新web页面的趋势。

XMLHTTP依赖于XMLHttpRequest完成从客户端的请求到服务端的应答。XMLHttpRequest提供了两个方法open和send。open方法用于初始化XMLHttpRequest
对象、指示请求的方式(get、post等)、安全性连接等,在调用open方法后必须调用send方法发送Http Request(Http请求)以返回Http Reponse(Http应答)。
看MSDN中对send方法的简介:
This method is synchronous or asynchronous, depending on the value of the bAsync parameter in the open call. If open is called with bAsync == False, this call does not return until the entire response is received or the protocol stack times out. If open is called with bAsync == True, this call returns immediately.
send方法是否同步或异步工作取决于open方法中的bAsync参数,如果bAsync == False表示send方法工作在同步状态下,发送http请求后,只有当客户端接收到来自服务端的全部应答数据或协议栈超时返回!反之bAsync == True,工作在异步状态下,直接返回。

实际运用中,设置bAsync = True, 使send方法被调用后XMLHttpRequest工作在异步状态,如果设为同步状态可能会导致不必要的长时间等待!

另外,无论在同步或异步请求工作状态下,XMLHttpRequest如何得到由服务端返回的应答数据?
看下面的示例代码:

<script>
var xmlhttp=null;
function PostOrder(xmldoc)
{
  varxmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  xmlhttp.Open("POST", "http://myserver/orders/processorder.asp", false);
  xmlhttp.onreadystatechange= HandleStateChange;
  xmlhttp.Send(xmldoc);
}
function HandleStateChange()
{
  if (xmlhttp.readyState == 4)
  {
    alert("Result = " + xmlhttp.responseXML.xml);
  }
}
</script>

服务端返回应答数据并完全被加载, 可通过XMLHttpRequest属性readState获知,其值变为4 - COMPLETED (已加载完成),
当readState变化时会调用XMLHttpRequest对象中的回调函数onreadstatechange,在函数中验证xmlhttp.readyState == 4,
这里得到的是XML文档(如果服务端有返回xml文档数据).

本文地址:http://com.8s8s.com/it/it43968.htm