当前位置: 代码迷 >> Java Web开发 >> xmlDoc.getElementsByTagName获得值为空,咋回事
  详细解决方案

xmlDoc.getElementsByTagName获得值为空,咋回事

热度:827   发布时间:2016-04-17 12:26:17.0
xmlDoc.getElementsByTagName获得值为空,怎么回事?
为什么判断if(XMLHttpReq.status == 200)的时候alert(XMLHttpReq.status)是0

我去掉了以上的这句话,通过alert(xmlDoc.getElementsByTagName("states").length);得到结果是0
就是说没获取到XML的内容,请问这是怎么回事啊?



以下是代码
<html>
<head>
<META http-equiv=Content-Type content="text/html; charset=UTF-8">
<script language="javascript">
var XMLHttpReq;
var requestType = "";

function createXMLHttpRequest() 
{

if (window.ActiveXObject)

XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest)
{
XMLHttpReq = new XMLHttpRequest();
}
}
function sendRequest(requestedList) 
{
requestType = requestedList;

createXMLHttpRequest();

XMLHttpReq.open("GET", "usa.xml", true);
XMLHttpReq.onreadystatechange = processResponse;
XMLHttpReq.send(null);  
}

function processResponse() 
{

if (XMLHttpReq.readyState == 4) 
{
if(XMLHttpReq.status == 200)
{
if(requestType == "north")
{
listNorthStates();
}
else if(requestType == "all")
{
listAllStates();
}
}
}
}
 
function listNorthStates()
{
var xmlDoc = XMLHttpReq.responseXML;
alert(xmlDoc);
var northNode = xmlDoc.getElementsByTagName("north")[0];
var out = "Northern States";
var northStates = northNode.getElementsByTagName("state");
outputList("Northern States", northStates);
}
 
function listAllStates()
{
var xmlDoc = XMLHttpReq.responseXML;
alert(xmlDoc.getElementsByTagName("states").length);
var allStates = xmlDoc.getElementsByTagName("states");
outputList("All States in Document", allStates);
}
 
function outputList(title, states)
{
var out = title;
var currentState = null;
for(var i = 0; i<states.length; i++)
{
currentState = states[i];
out = out + "\n-" + currentState.childNodes[0].nodeValue;
}
alert(out);
}
</script>
</head>
<body>
<form action="*">
<input type="button" value="all" onclick="sendRequest('all')">
<input type="button" value="north" onclick="sendRequest('north');">
</form>
</body>
</html>

usa.xml

<?xml version="1.0" encoding="UTF-8"?>
<states>
<north>
<state>Hinnesota</state>
<state>Ioma</state>
<state>North Dakota</state>
</north>
<sourth>
<state>Texas</state>
<state>Oklahoma</state>
<state>Louisiana</state>
</sourth>
<east>
<state>New York</state>
<state>North Carolina</state>
<state>Massachusetts</state>
</east>
<west>
<state>California</state>
<state>Oregon</state>
<state>Nevada</state>
</west>
</states>


------解决方案--------------------
  相关解决方案