(轉(zhuǎn))XMLHttpRequest basic
客戶端利用XMLHTTP發(fā)送請(qǐng)求得到服務(wù)端應(yīng)答數(shù)據(jù),并用Javascript操作DOM最終更新頁面- 又稱無刷新更新頁面,有代替?zhèn)鹘y(tǒng)web開發(fā)中采用form(表單)遞交方式更新web頁面的趨勢(shì)。
XMLHTTP依賴于XMLHttpRequest完成從客戶端的請(qǐng)求到服務(wù)端的應(yīng)答。XMLHttpRequest提供了兩個(gè)方法open和send。open方法用于初始化XMLHttpRequest
對(duì)象、指示請(qǐng)求的方式(get、post等)、安全性連接等,在調(diào)用open方法后必須調(diào)用send方法發(fā)送Http Request(Http請(qǐng)求)以返回Http Reponse(Http應(yīng)答)。
看MSDN中對(duì)send方法的簡(jiǎn)介:
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參數(shù),如果bAsync == False表示send方法工作在同步狀態(tài)下,發(fā)送http請(qǐng)求后,只有當(dāng)客戶端接收到來自服務(wù)端的全部應(yīng)答數(shù)據(jù)或協(xié)議棧超時(shí)返回!反之bAsync == True,工作在異步狀態(tài)下,直接返回。
實(shí)際運(yùn)用中,設(shè)置bAsync = True, 使send方法被調(diào)用后XMLHttpRequest工作在異步狀態(tài),如果設(shè)為同步狀態(tài)可能會(huì)導(dǎo)致不必要的長(zhǎng)時(shí)間等待!
另外,無論在同步或異步請(qǐng)求工作狀態(tài)下,XMLHttpRequest如何得到由服務(wù)端返回的應(yīng)答數(shù)據(jù)?
看下面的示例代碼:
<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>
服務(wù)端返回應(yīng)答數(shù)據(jù)并完全被加載, 可通過XMLHttpRequest屬性readState獲知,其值變?yōu)? - COMPLETED (已加載完成),
當(dāng)readState變化時(shí)會(huì)調(diào)用XMLHttpRequest對(duì)象中的回調(diào)函數(shù)onreadstatechange,在函數(shù)中驗(yàn)證xmlhttp.readyState == 4,
這里得到的是XML文檔(如果服務(wù)端有返回xml文檔數(shù)據(jù)).
posted on 2008-12-18 20:37 liujg 閱讀(151) 評(píng)論(0) 編輯 收藏