运用AJAX技术解析XML文件
这是数周前写的一个关于javascript程序了。”温故而知新”今天拿出来,温习温习,加深印象!其中三段关于AJAX的代码可以说是通用代码。
var xmlhttp;
//根据判断的浏览器的不同类型创建XMLHttpRequest对象
function createXMLHttpRequest(){
if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
}
//发起异步请求
function startAsyRequest(){
createXMLHttpRequest();//调用createXMLHttpRequest()XMLHttpRequest对象
xmlhttp.onreadystatechange = handleStateChange;
xmlhttp.open("GET", "bbc.xml?timespan=" + new Date().getTime(), true);
xmlhttp.send(null);
}
//XMLHttpRequest对象的readystate值变化时的处理函数
function handleStateChange(){
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
bbcAnalyze();//调用解析请求的XML文件的函数
}
else {
alert("请检查web服务器是否运行正常!");
}
}
}
//解析(利用XML DOM)请求的XML文件并利用HTML DOM以表格形式呈现数据
function bbcAnalyze(){
xmlDoc = xmlhttp.responseXML;
var table1 = document.getElementById("tb1");
//alert(xmlDoc);
if (xmlDoc) {
var countryNodes = xmlDoc.getElementsByTagName("Country");
//alert(countryNodes.length);
for (var i = 0; i < countryNodes.length; i++) {
var t1=document.createElement("tr");
var region = countryNodes[i].getAttribute("Region");
var td1 = document.createElement("td");
var newpnode1 = document.createTextNode(region);
td1.appendChild(newpnode1);
t1.appendChild(td1);
var name = xmlDoc.getElementsByTagName("Name")[i].childNodes[0].nodeValue;
var td2 = document.createElement("td");
var newpnode2 = document.createTextNode(name);
td2.appendChild(newpnode2);
t1.appendChild(td2);
var area = xmlDoc.getElementsByTagName("Area")[i].childNodes[0].nodeValue;
var td3 = document.createElement("td");
var newpnode3 = document.createTextNode(area);
td3.appendChild(newpnode3);
t1.appendChild(td3);
var population = xmlDoc.getElementsByTagName("Population")[i].childNodes[0].nodeValue;
var td4 = document.createElement("td");
var newpnode4 = document.createTextNode(population);
td4.appendChild(newpnode4);
t1.appendChild(td4);
if (xmlDoc.getElementsByTagName("GDP")[i].hasChildNodes()) {
var gdp = xmlDoc.getElementsByTagName("GDP")[i].childNodes[0].nodeValue;
var newpnode5 = document.createTextNode(gdp);
td5 = document.createElement("td");
td5.appendChild(newpnode5);
t1.appendChild(td5);
}
else {
gdp = "";
td6 = document.createElement("td");
var newpnode6 = document.createTextNode(gdp);
td6.appendChild(newpnode6);
t1.appendChild(td6);
}
table1.appendChild(t1);
//alert(table1);
}
}
else {
alert("xmlDoc文件为空,操作失败!");
}
}