`
wangtong40
  • 浏览: 248123 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

AJAX基础教程-2 ParseXML

阅读更多
js 代码
  1. <script type=< span="">"text/javascript">   
  2. var xmlHttp;   
  3. var requestType = "";   
  4. //创建xmlHttp对象   
  5. function createXMLHttpRequest() {   
  6.     if (window.ActiveXObject) {   
  7.     xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");   
  8.     }   
  9.     else if (window.XMLHttpRequest) {   
  10.     xmlHttp = new XMLHttpRequest();   
  11.     }   
  12. }   
  13. //开始相应解析parseXML.xml   
  14. function startRequest(requestedList) {   
  15.     requestType = requestedList;   
  16.     createXMLHttpRequest();   
  17.     xmlHttp.onreadystatechange = handleStateChange;   
  18.     xmlHttp.open("GET""parseXML.xml"true);   
  19.     xmlHttp.send(null);   
  20. }   
  21. //处理相关的操作   
  22. function handleStateChange() {   
  23.     if(xmlHttp.readyState == 4) {   
  24.         if(xmlHttp.status == 200) {   
  25.             if(requestType == "north") {   
  26.             listNorthStates();   
  27.             }   
  28.             else if(requestType == "all") {   
  29.             listAllStates();   
  30.             }   
  31.         }   
  32.     }   
  33. }   
  34. function listNorthStates() {   
  35.     var xmlDoc = xmlHttp.responseXML;//读取解析的xml信息   
  36.     var northNode = xmlDoc.getElementsByTagName("north")[0];   
  37.     var out = "Northern States";   
  38.     var northStates = northNode.getElementsByTagName("state");   
  39.     outputList("Northern States", northStates);   
  40. }   
  41. function listAllStates() {   
  42.     var xmlDoc = xmlHttp.responseXML;   
  43.     var allStates = xmlDoc.getElementsByTagName("state");   
  44.     outputList("All States in Document", allStates);   
  45. }   
  46. function outputList(title, states) {   
  47.     var out = title;   
  48.     var currentState = null;   
  49.     for(var i = 0; i < states.length; i++) {   
  50.     currentState = states[i];   
  51.     out = out + "\n- " + currentState.childNodes[0].nodeValue;   
  52.     }   
  53. alert(out);   
  54. }   
  55. </script>  
xml 代码
  1. <!---->xml version="1.0" encoding="UTF-8"?>  
  2. <states>  
  3.     <north>  
  4.         <state>Minnesotastate>  
  5.         <state>Iowastate>  
  6.         <state>North Dakotastate>  
  7.     north>  
  8.     <south>  
  9.         <state>Texasstate>  
  10.         <state>Oklahomastate>  
  11.         <state>Louisianastate>  
  12.     south>  
  13.     <east>  
  14.         <state>New Yorkstate>  
  15.         <state>North Carolinastate>  
  16.         <state>Massachusettsstate>  
  17.     east>  
  18.     <west>  
  19.         <state>Californiastate>  
  20.         <state>Oregonstate>  
  21.         <state>Nevadastate>  
  22.     west>  
  23. states>  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics