gpt4 book ai didi

javascript - 响应 XML 为空

转载 作者:行者123 更新时间:2023-12-03 16:36:01 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com