响应 XML 为空
responseXML is null
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.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 类型,而不是请求所需的 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/xml
或 application/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>
- 如果文本字段为空,则使用JavaScript应用CSS样式
- ReactJS映射:如何仅在url变量不为空时呈现html链接
- 如果localstorage为空,则显示欢迎消息
- 使用 jQuery 检查所有值是否为空或已填充
- 如果值为空,如何设置输入的默认值?jQuery
- 如何检查元素的内容是否为空,如果为空,请在jquery中删除该元素
- 在MVC 4中,对Controller的Ajax调用为空
- Spring Ajax列表返回,但对象为空
- 输入文本框为空时的阻止按钮asp.网络表单
- $_POST变量为空
- 如果数据为空,Ajax加载不会停止
- 边框颜色是't如果输入为空,则更改
- 如何在输入为空时停止发送
- 如果用户没有更改,则表单值为空
- 在jquery中获取文本输入val始终为空
- 下载被 Chrome 阻止的 xml 和 svg 文件的 zip 存档(无论是否为空)
- 检查XML节点在javascript中是否为空
- 响应XML为空,尽管responsetext是有效的.net webservice
- 响应 XML 为空
- 从PHP加载XML错误:Microsoft.XMLHTTP.DocumentElement为空