2012-05-19 42 views
0

我想要做的是從ajax請求中獲取XML以便從中提取數據(使用DOM,而不是它很重要)。不,我知道ajax工作得很好,因爲如果我嘗試獲取AjaxRequest.responseText,它就可以正常工作。那我收到錯誤消息說:Ajax XML響應爲NULL

「空」不是一個對象(評估「resturantsCategoriesAjaxXML.getElementsByTagName」)

,當我嘗試到的responseXML寫入日誌,我所得到的都是空的,就像它還沒有被定義一樣。我已經包含了處理AJAX的完整JS(對於奇怪的變量名稱抱歉,我只是不想在出現錯誤時更改它們)以及它正在提取的XML(簡單XML)。 非常感謝您的幫助:d

Java腳本:

resturantsCategoriesAjaxRequestAdress = "testFiles/categoriesAjax.xml"; 
resturantsCategoriesAjaxRequest = new XMLHttpRequest(); 
resturantsCategoriesAjaxRequest.onreadystatechange = function(){ 
if(resturantsCategoriesAjaxRequest.readyState == 4){ 
    resturantsCategoriesAjaxXML = resturantsCategoriesAjaxRequest.responseXML; 
    console.log(resturantsCategoriesAjaxRequest.responseXML); 
    categoriesArray = resturantsCategoriesAjaxXML.getElementsByTagName("category"); 
    categoriesArraylenght = categoriesArray.length; 
    alert(categoriesArraylenght); 
    categoriesArrayIritationControl = 0; 
    while (categoriesArraylenght >= categoriesArrayIritationControl) { 
     categoryName = categoriesArray[categoriesArrayIritationControl].getAttribut("name"); 
     //create new <li> object 
     //add to ctegories menu on restrants page 
     alert(categoryName); 
    } 
} 
} 
resturantsCategoriesAjaxRequest.open("GET", resturantsCategoriesAjaxRequestAdress, true); 
resturantsCategoriesAjaxRequest.overrideMimeType("text/xml"); 
resturantsCategoriesAjaxRequest.send(); 
console.log(resturantsCategoriesAjaxRequest.readyState); 

XML:

<?xml version='1.0'?> 
<category name="Fast_Food" id="1120"></category> 
<category name="Chinese" id="1108"></category> 
<category name="Italian" id="1230"></category> 
+0

你錯過了xml中的根元素。在這種形式下它是無效的。也許這就是responseXML爲null的原因。 – Andreas

+0

Dittos到Andreas的迴應。讓您的服務器端應用程序將標籤中的文本包裝起來。例如「 stuffyoudonow」。不是一個壞習慣。 –

回答

1

您的文檔是不正確的XML文檔,我認爲,你需要上面的父母標籤"<category>"

1

您需要一個封裝其他節點的根元素。

也許<categories></categories>結束,包含所有<category>節點。