2016-04-28 94 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