正如标题所示我试图从在线检索的xml中的属性返回特定值(第一次预测的分钟数)。
这是xml:
<?xml version="1.0" encoding="utf-8" ?>
<body copyright="All data copyright Societe de transport de Laval 2016.">
<predictions agencyTitle="Societe de transport de Laval" routeTitle="33Direction Métro Montmorency" routeTag="33N" stopTitle="De Villars / De Mexico [43246]" stopTag="CP43246">
<direction title="Nord">
<prediction epochTime="1459297620000" seconds="575" minutes="9" isDeparture="true" affectedByLayover="true" dirTag="33N_1_var0" vehicle="0307" block="L269" tripTag="33N2L26920420047" />
<prediction epochTime="1459301100000" seconds="4055" minutes="67" isDeparture="true" affectedByLayover="true" dirTag="33N_1_var0" vehicle="virtualVehicle_L268" block="L268" tripTag="33N2L26821400049" />
</direction>
</predictions>
</body>
这是我的代码,根据另一个回复来检索它:Get Attribute Value From Simple XML Using JQuery / Javascript。
$(document).ready(function(){
var url = "http://webservices.nextbus.com/service/publicXMLFeed?command=predictions&a=stl&stopId=43246";
//ajax way of getting data
$.ajax({
type: "GET",
url: url,
dataType: "xml",
success: function(xml) {
var string = xml;
//console.log(string);
var $doc = $.parseXML(string);
console.log($($doc).find('prediction').attr('minutes'));
}
});
});
</script>
我目前正未定义为对我上一次console.log的回复,我想我需要选择一个特定的&lt;预测分钟=“”&gt;,但我不确定如何?
答案 0 :(得分:0)
您的AJAX调用正在返回XML,而不是字符串。您需要将xml对象包装在jQuery对象中,而不是解析字符串,而不是$(xml)
。
然后,要获得第一个预测的分钟,您需要指定哪个预测。见.eq()
$xml.find('prediction').eq(0).attr("minutes");
$(document).ready(function() {
var url = "http://webservices.nextbus.com/service/publicXMLFeed?command=predictions&a=stl&stopId=43246";
//ajax way of getting data
$.ajax({
type: "GET",
url: url,
dataType: "xml",
success: function(xml) {
$xml = $(xml); // wrap xml in jQuery object
console.log($xml.find('prediction').eq(0).attr("minutes")); // specify the 1st prediction
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>