responseXML为null

时间:2011-08-07 13:49:27

标签: 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?

4 个答案:

答案 0 :(得分:4)

您的HTTP请求是异步的。在xmlhttp.responseXML的值为xmlhttp.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类型,而不是请求。另外,请尊重良好的编码习惯(不要忘记var,DRY等)

答案 1 :(得分:3)

确保PHP脚本中有header('Content-type: application/xml');。 另外,检查responseText - 也许你有错误?

答案 2 :(得分:1)

最近,我从Apache迁移到nginx并遇到了同样的问题。作为简单文件加载或从Apache服务器加载时,一切都很完美,但在nginx上运行时,responseXML始终为null。

我的特殊情况还涉及一个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;

答案 3 :(得分:0)

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

我不知道为什么,但是当您发送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>