2016-04-28 92 views
0

問題:它只爲每個元素附加「undefined」。Ajax和jQuery XML解析問題

我一直在閱讀鏈接兩小時的更好的一部分,試圖通過這個問題,但已經耗盡了資源。很抱歉,如果這個問題被問了很多。

我試圖獲取XML響應並將其轉化爲有意義的東西。到目前爲止,我已經使用data.gov數據集來測試它。

我的代碼:

<!DOCTYPE html> 
<html> 
<head> 
<title>jQuery and XML</title> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<meta name="language" content="en" /> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 
</head> 
<body 

<div id="output"></div> 

<script type="text/javascript"> 
$(document).ready(function(){ 
$.ajax({ 
    type: "GET", 
    dataType: "xml", 
    url: "https://health.data.ny.gov/api/views/wssx-idhx/rows.xml", 
    success: function(xml){ 
     $(xml).find("row").each(function(){ 
      $("#output").append($(this).attr("facility_name") + "<br />");   
     }); 
    } 
}); 
}); 
</script> 


</body> 
</html> 

例如,我與測試網址給出了這樣的迴應:

<response> 
<row> 
    <row _id="48" _uuid="760E4665-B5D8-489A-ACC3-9D649D4F1989" _position="48" _address="http://health.data.ny.gov/resource/wssx-idhx/48"> 
    <facility_name>Orchard Grove Residences</facility_name> 
    <address>2000 Southwestern Drive W. E.</address> 
    <county>Chautauqua</county> 
    <city>Jamestown</city> 
    <zip>14701</zip> 
    <.....> 
</row> 
<response> 

這只是在XML響應許多因素之一。我覺得這裏有一些簡單的東西,我錯過了,否則某些東西在我的思維過程中是根本錯誤的。

+0

有點偏離主題,但有你使用jQuery的版本,從[2010年2月](https://github.com/jquery/jquery/releases?after=1.4.4rc3理由)(1.4.2)? –

+0

我一直在經歷一些教程。必須粘貼一個非常舊的鏈接到圖書館,因爲該教程可能是在那個時候編寫的。感謝您的領導! – nethageraba

回答

0

您想在XML中追加每個rowfacility_name孩子的文字。因此您不能使用attr。相反,寫

$("#output").append($(this).find("facility_name").text() + "<br />"); 
+0

啊,我知道我的某個地方有一個根本性的誤解。謝謝,這使得現在更加合理。 – nethageraba

0

facility_name不是row的屬性,它是一個子節點。 $(this).attr("facility_name")將檢索看起來像<row facility_name=""...>,這不是你想要的東西。

您需要使用$(this).find("facility_name")來獲取子節點。因爲只有一個你可以得到數組中的第一個項目,而不是做另一個.each

+0

現在對我來說很有意義。謝謝! – nethageraba