无法使用javascript在网页中显示xml数据

时间:2015-10-16 07:24:21

标签: javascript html xml

我试图通过访问xml dom并使用javascript将该数据显示为表格格式来显示包含一些信息的xml文件。通过创建一个xml http请求编写下面的函数来尝试,但仍然无法获得任何输出来显示数据....

<html>
<head>
</head>
<body>
<p>Please enter id(100 or 105)</p>
<p>Input id (106) to view the entire details</p>
<script type="text/javascript">
function display()
{
var y=document.getElementById('hifi').value
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","user.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML; 
var x=xmlDoc.getElementsByTagName("Persondetails");
document.write("<table><tr><th>id</th><th>name</th></tr>");
for(i=0;i<x.length;i++)
{
var z=x[i].getElementsByTagName("id")[0].childNodes[0].nodeValue;
if(z==y)
{
document.write("<tr><td>");
document.write(x[i].getElementsByTagName("id")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("name")            [0].childNodes[0].nodeValue);
document.write("</td></tr>");
}
else if(y==106)
{
document.write("<tr><td>");
document.write(x[i].getElementsByTagName("id")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("name")    [0].childNodes[0].nodeValue);
document.write("</td></tr>");
}
else if(y<100 || y>106)
{
window.alert("Input is invalid");
}
}
document.write("</table>");
}
</script>
<form name="myform">
        Enter id :<input id="hifi" type="number" min="100" max="106"/>
                   <input type="button" value="Submit" onclick="display()"/>
 </form>


</body>
</html>



 <?xml version="1.0" encoding="UTF-8"?>
 <student>
 <Persondetails>
 <id>100</id>
 <name>tamizh</name>
 </Persondetails>
 <Persondetails>
 <id>101</id>
 <name>amal</name>
 </Persondetails>
 <Persondetails>
 <id>102</id>
 <name>ice cream</name>
 </Persondetails>
 <Persondetails>
 <id>103</id>
 <name>haa</name>
 </Persondetails>
 <Persondetails>
 <id>104</id>
 <name>rocky</name>
 </Persondetails>
 <Persondetails>
 <id>105</id>
 <name>ra</name>
 </Persondetails>
 <Persondetails>
 <id>106</id>
 <name>r</name>
 </Persondetails>
 </student>

0 个答案:

没有答案