我正在使用XMLHttpRequest从JSP获取带有XML内容的responseXML。但是无法从responseXML Object获取节点值。即使根节点显示为null。
我正在使用IE8。 以下是我正在使用的代码。
function function2(){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
var xhrResponse=xhr.responseXML;
alert(xhr.responseText);
alert(xhrResponse==null);
alert(xhr.getAllResponseHeaders());
var theRoot = xhrResponse.documentElement;
alert(theRoot);
alert(theRoot.getElementsByTagName("Name")[0].childNodes[0].nodeValue);
alert(xhrResponse.getElementsByTagName("Name").length);
}
}
}
xhr.open("GET", "jspXML.jsp" ,true);
xhr.setRequestHeader("Content-Type", "text/xml");
xhr.send();
}
服务器端脚本:
<%@ page contentType="text/xml" %>
<?xml version="1.0" encoding="UTF-8"?>
<%response.setContentType("text/xml"); %>
<College>
<Student>
<Name>A</Name>
<Age>10</Age>
</Student>
<Student>
<Name>B</Name>
<Age>20</Age>
</Student>
<Student>
<Name>C</Name>
<Age>30</Age>
</Student>
</College>
从警报消息中,发现responseXML为非空且它是{object]。但是根元素(使用documentElement)为空。
但是responseText显示正确。
1.这种行为依赖于浏览器吗?
2.当我搜索这个问题时,许多解决方案都建议将请求标头设置为“text / xml”。根据我的理解,使用响应标头检索responseXML。所以,我是否真的需要设置请求标头或者设置响应头是正确的方法吗?
有谁可以告诉我是否遗漏了什么?谢谢。
答案 0 :(得分:1)
如果查看javascript控制台或调试器,问题是xml文档无效。 XML声明必须是文档中的第一件事,但是您的文档以@page
指令和xml声明之间的换行符形式的空格开头。解决方案非常简单:
<%@ page contentType="text/xml" %><?xml version="1.0" encoding="UTF-8"?>
<College>
<Student>
<Name>A</Name>
<Age>10</Age>
</Student>
<Student>
<Name>B</Name>
<Age>20</Age>
</Student>
<Student>
<Name>C</Name>
<Age>30</Age>
</Student>
</College>
现在指令和声明之间没有换行符。另请注意,用于设置内容类型的scriptlet不是必需的 - @page
指令已经为您设置了它。