(轉)XMLHttpRequest basic
客戶端利用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文檔數據).