XMLHttpRequest 對象
XMLHttpRequest 對象用于在后臺與服務(wù)器交換數(shù)據(jù)。
什么是 XMLHttpRequest 對象?
XMLHttpRequest 對象用于在后臺與服務(wù)器交換數(shù)據(jù)。
XMLHttpRequest 對象是開發(fā)者的夢想,因為您能夠:
- 在不重新加載頁面的情況下更新網(wǎng)頁
- 在頁面已加載后從服務(wù)器請求數(shù)據(jù)
- 在頁面已加載后從服務(wù)器接收數(shù)據(jù)
- 在后臺向服務(wù)器發(fā)送數(shù)據(jù)
所有現(xiàn)代的瀏覽器都支持 XMLHttpRequest 對象。
如需學習更多有關(guān) XMLHttpRequest 對象的知識,請學習我們的 XML DOM 教程。
創(chuàng)建 XMLHttpRequest 對象
所有現(xiàn)代瀏覽器 (IE7+、Firefox、Chrome、Safari 以及 Opera) 都內(nèi)建了 XMLHttpRequest 對象。
通過一行簡單的 JavaScript 代碼,我們就可以創(chuàng)建 XMLHttpRequest 對象。
創(chuàng)建 XMLHttpRequest 對象的語法:
xmlhttp=new XMLHttpRequest();
老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 對象:
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
提示:在下一章,我們將使用 XMLHttpRequest 對象從服務(wù)器取回 XML 信息。
實例 1
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url)
{
xmlhttp=null;
if (window.XMLHttpRequest)
{// code for all new browsers
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE5 and IE6
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange=state_Change;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
}
function state_Change()
{
if (xmlhttp.readyState==4)
{// 4 = "loaded"
if (xmlhttp.status==200)
{// 200 = OK
// ...our code here...
}
else
{
alert("Problem retrieving XML data");
}
}
}
</script>
注釋:onreadystatechange 是一個事件句柄。它的值 (state_Change) 是一個函數(shù)的名稱,當 XMLHttpRequest 對象的狀態(tài)發(fā)生改變時,會觸發(fā)此函數(shù)。狀態(tài)從 0 (uninitialized) 到 4 (complete) 進行變化。僅在狀態(tài)為 4 時,我們才執(zhí)行代碼。
為什么使用 Async=true ?
我們的實例在 open() 的第三個參數(shù)中使用了 "true"。
該參數(shù)規(guī)定請求是否異步處理。
True 表示腳本會在 send() 方法之后繼續(xù)執(zhí)行,而不等待來自服務(wù)器的響應(yīng)。
onreadystatechange 事件使代碼復(fù)雜化了。但是這是在沒有得到服務(wù)器響應(yīng)的情況下,防止代碼停止的最安全的方法。
通過把該參數(shù)設(shè)置為 "false",可以省去額外的 onreadystatechange 代碼。如果在請求失敗時是否執(zhí)行其余的代碼無關(guān)緊要,那么可以使用這個參數(shù)。
XML / ASP
您也可以把 XML 文檔打開并發(fā)送到服務(wù)器上的 ASP 頁面,分析此請求,然后傳回結(jié)果。
<html>
<body>
<script type="text/javascript">
xmlHttp=null;
if (window.XMLHttpRequest)
{// code for IE7, Firefox, Opera, etc.
xmlHttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{// code for IE6, IE5
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp!=null)
{
xmlHttp.open("GET", "note.xml", false);
xmlHttp.send(null);
xmlDoc=xmlHttp.responseText;
xmlHttp.open("POST", "demo_dom_http.asp", false);
xmlHttp.send(xmlDoc);
document.write(xmlHttp.responseText);
}
else
{
alert("Your browser does not support XMLHTTP.");
}
</script>
</body>
</html>
ASP 頁面,由 VBScript 編寫:
<%
set xmldoc = Server.CreateObject("Microsoft.XMLDOM")
xmldoc.async=false
xmldoc.load(request)
for each x in xmldoc.documentElement.childNodes
if x.NodeName = "to" then name=x.text
next
response.write(name)
%>
通過使用 response.write 屬性把結(jié)果傳回客戶端。
XMLHttpRequest 對象是 W3C 的標準嗎?
任何 W3C 推薦標準均未規(guī)定 XMLHttpRequest 對象。
不過,W3C DOM Level 3 的 "Load and Save" 規(guī)范包含了一些相似的功能性,但是還沒有任何瀏覽器實現(xiàn)它們。