您好我有一个json对象,返回如下;
{
"status": "ok",
"data": {
"mapdata": [
{
"name": "Test title",
"description": "Lorem ipsum dolor sit amet",
"lat": "51.297387",
"lng": "-0.737240"
}
{
"name": "Example Event 5",
"description": "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget tincidunt turpis. Nam tincidunt non diam eu mollis. Suspendisse lobortis rhoncus ante at auctor. </p>\r\n",
"lat": "51.5232032",
"lng": "-0.6053448999999773"
}
]
}
}
我想循环数据数组,但我不确定如何,这是我到目前为止的代码:
$.ajax({
url: '/googlemaps',
type: 'POST',
dataType: 'json',
success: function (response) {
for (var key in response.data) {
console.log(key.name);
var latLng = new google.maps.LatLng(key.lat, key.lng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.name
});
//send details to infoBox function to create infoWindow
infoBox(map, marker, data);
} // end for
} //end success
})
然而,当我循环键并尝试将lat和lng传递给google maps函数时,它会输出此错误:
Uncaught TypeError: Cannot read property 'lat' of undefined
并且console.log
未定义console.log(key.name);
。任何想法我做错了什么以及我如何循环mapdata数组?
答案 0 :(得分:1)
您正在尝试循环访问对象(response.data)而不是数组(response.data.mapdata)。另外,我使用了正常的for循环。所以我相信这应该有效:
for(var i = 0; i < object.data.mapdata.length; i++) {
console.log(object.data.mapdata[i].name);
var latLng = new google.maps.LatLng(object.data.mapdata[i].lat, object.data.mapdata[i].lng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: object.data.mapdata[i].name
});
//send details to infoBox function to create infoWindow
infoBox(map, marker, data);
} // end for
答案 1 :(得分:1)
一切都很好。我只想告诉你循环部分:
var mapdata = response.data.mapdata;
$.each(mapdata, function(index, mapinfo){
// Here you can find all your variables...
console.log(mapinfo.name);
console.log(mapinfo.lat);
console.log(mapinfo.lng);
});
希望这会有所帮助......但如果我是你,我会做的是:
if(response.status == 'ok') {
if (response.data.mapdata.length > 0) {
// Here the above code of mine will go..
} else {
// There is no map data to display.
}
} else {
// Do something to notify that there is an error in the response
}