注意html引用xml的路径加“”引号
注意getElementsByTagName 里面参数也加引号
html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <Meta http-equiv="content-type" content="text/xml;charset=gb2312"> <title>Title</title> <script language="JavaScript"> var xmlhttp; function createxmlrequest(){ if(window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest(); } else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } function getxml(xmlUrl){ var url="/ajax/chap103.xml"; createxmlrequest(); xmlhttp.onreadystatechange=HandleStateChange; xmlhttp.open("GET",url,true); xmlhttp.send(null); } function HandleStateChange(){ if(xmlhttp.readyState==4&&xmlhttp.status==200){ drawtable(xmlhttp.responseXML); return true; } } function drawtable(myxml){ var objstudents=myxml.getElementsByTagName("student"); var objstudent="",stuid="",stuname="",stuchinese="",stumaths="",stuenglish=""; for(var i=0;i<objstudents.length;i++){ objstudent=objstudents[i]; stuid=objstudent.getElementsByTagName("id")[0].firstChild.nodeValue; stuname = objstudent.getElementsByTagName("name")[0].firstChild.nodeValue; stuchinese = objstudent.getElementsByTagName("chinese")[0].firstChild.nodeValue; stumaths = objstudent.getElementsByTagName("math")[0].firstChild.nodeValue; stuenglish = objstudent.getElementsByTagName("english")[0].firstChild.nodeValue; addrow(stuid,stuname,stuchinese,stumaths,stuenglish); } } function addrow(stuid,stuenglish){ var objtable=document.getElementById("score"); var objrow=objtable.insertRow(objtable.rows.length); var stuinfo=new Array(); stuinfo[0]=document.createTextNode(stuid); stuinfo[1]=document.createTextNode(stuname); stuinfo[2]=document.createTextNode(stuchinese); stuinfo[3]=document.createTextNode(stumaths); stuinfo[4]=document.createTextNode(stuenglish); for(var i=0;i<stuinfo.length;i++){ var objcol=objrow.insertCell(i); objcol.appendChild(stuinfo[i]); } } </script> </head> <body> <form> <p> <input type="button" id="btn" onclick="getxml();"> </p> <p> <table id="score"> <tr> <th>id</th> <th>name</th> <th>chinese</th> <th>math</th> <th>english</th> </tr> </table> </p> </form> </body> </html>
xml
<?xml version="1.0" encoding="gb2312" ?> <list> <caption>scorelist</caption> <student> <id>001</id> <name>MissZhou</name> <chinese>99</chinese> <math>99</math> <english>99</english> </student> </list>原文链接:https://www.f2er.com/ajax/162129.html