2014-06-29 104 views
-1

我想用jQuery解析xml文檔。 xml通過Ajax請求獲得:用jQuery解析Ajax xml響應

$.ajax({ 
    url: address, 
type: 'GET', 
dataType: 'xml', 
success: function(data) { 
    console.log(data); 
    } 

});

如果我把瀏覽器的請求,我得到這樣的迴應:

This XML file does not appear to have any style information associated with it. The document tree is shown below. 
<root> 
    <c>208</c> 
    <lst> 
     <s> 
     <id>92</id> 
     <t>3</t> 
     <ot>06,00</ot> 
     <ct>21,30</ct> 
     <cat>Electronics</cat> 
     </s> 
... 

現在,我在幾個方面來解析XML響應已經嘗試過,比如我試圖登錄的控制檯元素與標籤'噸',但我沒有成功。

我試過,到成功的功能:

var tag = $(data).find('t'); 
console.log(tag); 

,但是這給了我一個空數組

也該解決方案給我一個空數組:

var parser=new DOMParser(); 
var xmlDoc=parser.parseFromString(data.responseText,"text/xml"); 
console.log(xmlDoc); 
console.log($(xmlDoc).find('t')); 

有誰知道正確的如何解析這個XML文檔?

回答

1

已解決,問題在於我試圖以錯誤的方式創建跨域XML請求。此代碼爲我工作:

var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from xml where url="' + address + '"') + '&format=xml&callback=?'; 

    // Request that YSQL string, and run a callback function. 
    // Pass a defined function to prevent cache-busting. 
    $.getJSON(yql, function (data) { 
     var xml = data.results[0]; 
     console.log(xml); 
     console.log($(xml).find('t')[0].innerHTML); 

    }); 

我希望這會幫助別人有同樣的問題