剛開始只知道Ajax訪問.do或者.jsp之類的,今天看到了訪問xml檔案 的.
var url = "MyXML.xml"; //URL指向xml檔案路徑
createXMLHttpRequest();
XMLHttpReq.onreadystatechange = processResponse;
XMLHttpReq.open("GET",url,true);
XMLHttpReq.send(null);
xml檔案格式:
<?xml version="1.0" encoding="GB2312"?>
<classmates>
<student>
<sid>1</sid>
<sname>reqe</sname>
<gre>1700</gre>
<tse>120</tse>
</student>
<student>
<sid>2</sid>
<sname>rqerwe</sname>
<gre>1800</gre>
<tse>120</tse>
</student>
<student>
<sid>3</sid>
<sname>iuir</sname>
<gre>1700</gre>
<tse>120</tse>
</student>
</classmates>
解析:
var students = XMLHttpReq.responseXML.getElementsByTagName("student"); //得到所有的student結點數組
for(var i =0;i<students.length;i++)
{
var stud = students[i]; //得一個stutdent結點
var name = stud.getElementsByTagName("sname")[0].firstChild.data; //取結點裡的資料
var gre = stud.getElementsByTagName("gre")[0].firstChild.data;
var tse = stud.getElementsByTagName("tse")[0].firstChild.data;
}