注意: xml 声明通常在 xml 文档的第一行出现. xml 声明不是必选项, 但是如果使用 xml 声明, 必须在文档的第一行, 前面不得有空格空行.
出现问题场景: 用 Ajax 请求服务端的 xml 数据
- <!DOCTYPE html>
- <HTML lang="en">
- <head>
- <meta charset="UTF-8">
- <title>
- Ajax 请求 xml 数据
- </title>
- </head>
- <body>
- <script>
- var xhr = new XMLHttpRequest();
- xhr.open('GET', 'data.php');
- xhr.send();
- xhr.onreadystatechange = function() {
- if (this.readyState != 4) return;
- // console.log(this.responseText);
- //this.responseXML 专门获取服务端返回的 xml 数据, 操作方式是通过 dom 的方式操作
- // 但是需要服务端的响应头中的 Content-Type 设置为 application/xml
- console.log(this);
- }
- </script>
- </body>
- </HTML>
注意: 下面的 xml 声明前有空行
- <?PHP
- // 不管服务端返回的数据是哪种类型, 都在 content-type 写清楚
- header('Content-Type: application/xml');
- ?>
- <?xml version="1.1" encoding="utf-8"?>
- <person>
- <student > 石羊 </student>
- <age>18</age>
- <gender > 男 </gender>
- </person>
这时候输出的内容 responseXML 的值为 null, 出现了不是想要的结果!!!
1.PNG
去掉 xml 声明前的空格后: 出现了想要的结果.
2.PNG
来源: http://www.jianshu.com/p/74e48e5af7c5