响应 XML 为空

responseXML is null

本文关键字:为空 XML 响应      更新时间:2023-09-26
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返回为空吗?

您的 HTTP 请求是异步的。 xmlhttp.responseXMLxmlhttp.readyState具有 4 的值之前不会有一些值。

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 类型,而不是请求所需的 XML MIME 类型。另外,请尊重良好的编码实践(不要忘记var,DRY等(

确保 PHP 脚本中有header('Content-type: application/xml');。此外,检查响应文本 - 也许您有错误?

最近,我从Apache迁移到nginx,遇到了同样的问题。当作为简单文件或从Apache服务器加载时,一切都运行良好,但是在nginx上运行时responseXML总是为空。

我的具体情况还涉及一个XSL样式表来转换XML:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="main-template-transformer.xsl"?>

常规 XML 文件的内容类型恢复得很好。但是,重要的是 XSL 文件的内容类型。(这是通过检查responseText发现的,该不是空的,并且包含 XSL 文件的整个文本。检查此文件上的HTTP标头显示内容类型在Apache和nginx之间发生了变化。

内容类型应为 text/xmlapplication/xml 。nginx 1.10.3 中的默认值是 application/octet-stream ,这将导致responseXML始终为空。

这可以通过在 JavaScript 文件中添加以下行来修复:

xmlhttp.overrideMimeType('text/xml');

这可以通过在"conf/mime.types"中的nginx服务器配置中添加以下行来修复:

    text/xml                              xsl;

我刚刚测试并找到了解决方案。

我不知道为什么,但是当你发送xml标头时,XMLHttpRequest无法解析它。

要使用 XMLHttpRequest 的 DOM responseXML 属性,您必须删除 xml 标头。

在您的情况下,xml 响应将是

<main>
    <food>
        <type>6</type>
        <region>5676</region>
    </food>
    <food>
        <type>6</type>
        <region>5676</region>
    </food>
</main>