xml宣告之前不能有空格空行
注意: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