【发布时间】:2013-10-14 12:36:22
【问题描述】:
我正在使用 XMLHttpRequest 从具有 XML 内容的 JSP 中获取 responseXML。但无法从 responseXML 对象中获取节点值。甚至根节点也显示为 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 是使用响应标头检索的。所以,我真的需要设置请求标头吗或者设置响应头是正确的方法?
谁能告诉我是否遗漏了什么?谢谢。
【问题讨论】:
标签: xml jsp xmlhttprequest