本文介绍了responseXML的是空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

url = "http://localhost/xml.php?type=xml";
if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest();
      xmlhttp.open("GET", url, true);
      xmlhttp.setRequestHeader('Content-Type', 'text/xml');
      xmlhttp.send(null);
}
else if (window.ActiveXObject)  {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    if (xmlhttp) {
        xmlhttp.open("GET", url, true);
        xmlhttp.setRequestHeader('Content-Type', 'text/xml');
        xmlhttp.send();
    }
}

alert(xmlhttp.responseXML); //returns null

XML文件

XML file

<?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.responseXML 会不会有一定的价值,直到 xmlhttp.readyState 4的值

Your HTTP request is asynchronous. xmlhttp.responseXML won't have some value until xmlhttp.readyState has the value of 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();
}

Additionaly,我不认为你需要的 setRequestHeader 行。的XML MIME类型所需的反应,而不是对请求。另外,请遵守良好的编码习惯(别忘了 VAR ,干,等。)

Additionaly, I don't think you need the setRequestHeader line. XML MIME type is required for response, not for request. Also, please respect good coding practices (don't forget var, DRY, etc.)

这篇关于responseXML的是空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 08:58