url = "http://localhost/xml.php?type=xml";
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader('Content-Type', 'application/xml');
xmlhttp.send(null);
}
else if (window.ActiveXObject) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (xmlhttp) {
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader('Content-Type', 'application/xml');
xmlhttp.send();
}
}
alert(xmlhttp.responseXML); //returns null
XML 文件
<?xml version="1.0" encoding="UTF-8" ?>
<main>
<food>
<type>6</type>
<region>5676</region>
</food>
<food>
<type>6</type>
<region>5676</region>
</food>
</main>
有人知道为什么 xmlhttp.responseXML
返回 null 吗?
最佳答案
您的 HTTP 请求是异步的。在 xmlhttp.readyState
具有值 4
之前,xmlhttp.responseXML
不会具有任何值。
var url = "http://localhost/xml.php?type=xml";
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp) {
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.responseXML);
}
};
xmlhttp.send();
}
此外,我认为您不需要 setRequestHeader
行。 XML MIME 类型是响应所必需的,而不是请求所必需的。另外,请尊重良好的编码习惯(不要忘记 var
、DRY 等)
关于javascript - 响应 XML 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10042733/