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

相关文章:

javascript - AJAX调用后如何制作弹出框动画?

jQuery 提交表单无需重新加载页面

javascript - 使用 Node.js 将客户端数据保存在服务器端

javascript - ajax请求周期自动刷新时如何使用knockout.js数据绑定(bind)?

javascript - JS 仅在点击时加载图像

javascript - 返回php变量?

javascript - 回显由curl返回的javascript代码

javascript - 使用 AJAX/JSON 进行 PHP 验证

ajax - 检查 Typeahead 中是否存在文本框的值

javascript - 正则表达式中的多个条件 - 如何用破折号替换冒号和空格