javascript - 响应 XML 为空

标签 javascript ajax

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/6973202/

相关文章:

javascript - moment 对象数组具有未定义的元素

javascript - 在asp.net中加载div而不刷新页面

javascript - 动态使点击的节点作为加载节点的父节点 - jsTree

javascript - 循环时对 localStorage 中的数值求和

javascript - jwplayer 从 yell cdn 流式传输

javascript - Firebug 不会加载 JavaScript 文件或在断点处停止执行

javascript - 当用户单击“提交”时,我的 AJAX 未发布或响应

javascript - AJAX 请求不会更改 div 中的文本

jquery - Ajax get 调用返回整个 html 页面

php - Ajax 响应前的空格(jQuery、PHP)