我有一个json文件:
{"markers":[
{ "latitude":11.58655, "longitude":122.755402, "type":"A"},
{ "latitude":11.00698, "longitude":124.612801, "type":"B"},
{ "latitude":10.30723, "longitude":123.898399, "type":"A"},
{ "latitude":11.24775, "longitude":125.003502, "type":"C"},
{ "latitude":11.03693, "longitude":125.719498, "type":"Z"}
]}
和ajax请求:
$.ajax({
type: "POST",
url: 'data.txt',
dataType: 'json',
success: function(data){ locations.length = 0;
for (p = 0; p < data.markers.length; p++) {
locations.push(Array(data.markers[p].latitude,data.markers[p].longitude));
var marker = new google.maps.Marker({
position: new
google.maps.LatLng(data.markers[p].latitude,data.markers[p].longitude),
map: map, title:"marker "+p }); } },
error: function (xhr,status,errorStr) {
alert("status="+status+", error="+errorStr)
}
});
这对我来说很好,但我需要根据他们的 TYPE 获取数据。如果我有办法可以根据“ A “所以我只获得 TYPE = A
的数据答案 0 :(得分:2)
您可以使用jQuery.grep()
var filteredData = $.grep( data, function( d, i ) {
return d.TYPE == 'A';
});
并循环变量filteredData
答案 1 :(得分:0)
for (p = 0; p < data.markers.length; p++) { // this is your code
if(data.markers[p].type == 'A'){
//do stuff with type : A only
}
}
答案 2 :(得分:0)
最简单的方法是检查循环内部
$.ajax({
type: "POST",
url: 'data.txt',
dataType: 'json',
success: function(data){ locations.length = 0;
for (p = 0; p < data.markers.length; p++) {
if(data.markers[p].type === 'A'){
locations.push(Array(data.markers[p].latitude,data.markers[p].longitude));
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.markers[p].latitude,data.markers[p].longitude), map: map, title:"marker "+p
});
}
}
},
error: function (xhr,status,errorStr) {
alert("status="+status+", error="+errorStr)
}
});