【AJAX】讀取XML
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc()
{
//判斷瀏覽器
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//等待
document.getElementById("myDiv").innerHTML="讀取中...";
//載入
xmlhttp.open("GET","cd.xml",true);
//處理
xmlhttp.onreadystatechange=function(){ handleStateChange(); };
//設定表頭
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8")
//傳送
xmlhttp.send();
}
function handleStateChange() //處理動作--讀取XML
{
// readyState: 4 代表 request finished and response is ready
// status: 200 代表 Ok
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
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;
}
}
</script>
部分HTML碼 :
<h2>My CD Collection:</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Get my CD collection</button>
XML檔內容 :

執行畫面(初始) :

執行畫面(按下按鈕) :
留言
張貼留言