點擊彈出新頁面中的“See Author”鏈接,你將會看到該頁面作者。從頁面提交到顯示從服務器獲得的結果,這段過程你將不會發現頁面的重刷新。
<script type="text/javascript">
function findAuthor(file){
var xmlObj = null;
if(window.XMLHttpRequest){
xmlObj = new XMLHttpRequest();
} else if(window.ActiveXObject){
xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
} else {
return;
}
xmlObj.onreadystatechange = function(){
if(xmlObj.readyState == 4){ <!-- 描述一個已加載的狀態 -->
updateObj('author',
xmlObj.responseXML.getElementsByTagName('name')[0].firstChild.data);
}
}
xmlObj.open ('GET', file, true);
xmlObj.send (''); <!-- 向服務器發出請求 -->
}
function updateObj(obj, data){
var textNode = document.createTextNode(data); <!-- 文本內容data轉換成Dom對象 -->
document.getElementById(obj).appendChild(textNode);
}
</script>
創建好XMLHttpRequest對象xmlObj之後,會調用函數監聽該對象狀態的變化,onreadystatechange
是一個事件句柄。它的值是一個函數function(){...},當 XMLHttpRequest 對象的狀態發生改變時,會觸發此函數。狀態從 0 (uninitialized) 到 4 (complete) 進行變化。僅在狀態爲 4 時,我們才執行代碼。
我們的實例在 open() 的第三個參數中使用了 "true"。
該參數規定請求是否異步處理。
True 表示腳本會在 send() 方法之後繼續執行,而不等待來自服務器的響應。