由 Ghostzhang 发表于 2006-03-21 01:27
刚开始学XMLHTTP,试写的一个读取XML的JS脚本,没什么技术含量,主要用来读取一个类似于通讯录的XML文件。
xml
<?xml version="1.0" encoding="utf-8" ?> <hhitshop> <name>aa</name> <phone>01234567</phone> <fax>01234567</fax> <address>aaaaa</address> </shop> <name>bb</name> <phone>12345678</phone> <fax>12345678</fax> <address>bbbbb</address> </shop> <name>cc</name> <phone>23456789</phone> <fax>23456789</fax> <address>ccccc</address> </shop> </hhitshop>
Javascript
var xmlHttp; //创建对象 function createXMLHttpRequest(){ if (window.ActiveXObject){ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }else if (window.XMLHttpRequest){ xmlHttp = new XMLHttpRequest("Msxml2.XMLHTTP.3.0"); //发请请求 function doSearch(url){ createXMLHttpRequest(); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.open("GET",url,"true"); xmlHttp.send(null); //处理响应 function handleStateChange(){ if (xmlHttp.readyState == 4){ if (xmlHttp.status == 200){ parseResults(); //取得URL function createURL(text){ var url; url = "BranchAreaInfo.asp?AreaID="; if (text != ""){ url += escape(text); doSearch(url); //读取XML文件 function parseResults(){ var results = xmlHttp.responseXML; var sDiv = ""; var shop = "null"; var name =""; var address = ""; var phone = ""; var fax = ""; var hhitshop = results.getElementsByTagName("shop"); for (var i = 0; i< hhitshop.length; i++){ shop = hhitshop[i]; name = shop.getElementsByTagName("name")[0].firstChild.nodeValue; phone = shop.getElementsByTagName("phone")[0].firstChild.nodeValue; fax = shop.getElementsByTagName("fax")[0].firstChild.nodeValue; address = shop.getElementsByTagName("address")[0].firstChild.nodeValue; sDiv += addDiv(name,photo,address,phone,fax); document.getElementById("results").innerHTML = sDiv; //输出格式化 function addDiv(name,photo,address,phone,fax){ var WDiv = "<div class='shop_list'>"; WDiv += "<a href='#'><img alt='"+ name +"' src='"+ photo +"' /></a>"; WDiv += "<dl>"; WDiv += "<dt><a href='#'>名称</a></dt>"; WDiv += "<dd>电话:"+ phone +"</dd>"; WDiv += "<dd>传真:"+ fax +"</dd>";