8.服務器響應 response 獲得服務端的響應信息,使用XMLHttpRequest 對象的 responseText 或者responseXML 屬性
responseText屬性如果服務端的響應不是xml,就可以使用responseText 屬性。 responseText 屬性返回響應信息是一個字符串document.getElementById("myDiv").innerHTML=xmlhttp.responseText; responseXML屬性如果服務端響應是xml,可以使用responseXML 屬性。 Request the file cd_catalog.xml and parse the response: xmlDoc=xmlhttp.responseXML; txt=""; x=xmlDoc.getElementsByTagName("ARTIST"); for (i=0;i<x.length;i++) { txt=txt + x[i].childNodes[0].nodeValue + "<br />"; } document.getElementById("myDiv").innerHTML=txt; 9.onreadystatechange事件 當響應發(fā)送到服務器,我們要在響應結果的基礎上執(zhí)行一些動作,使用onreadystatechange事件 onreadystatechange事件被觸發(fā),當每次readyState變化時。 readyState屬性保存的是XMLHttpRequest對象的狀態(tài) XMLHttpRequest對象的三個重要的屬性:
當readyState為4和狀態(tài)是200,響應已準備就緒: Example例子xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } 10.使用回調函數Callback Function一個回調的函數,被看過另一個函數的參數。如果程序當中有多個ajax任務,可以定義一個標準函數,以便通用 function myFunction() { loadXMLDoc("ajax_info.txt",function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } }); } |
|