ajax post返回json编码的位置数据,如:
[{"name":"Chris","data":{"user":"447967048843","data":[{"timestamp":1332840872,"longitude":-1.549517,"latitude":53.973174},{"timestamp":1332841510,"longitude":-1.444133,"latitude":53.997148}]},"contacts":null},{"name":"Jason","data":{"user":"447879896697","data":[{"timestamp":1332839836,"longitude":-1.566667,"latitude":53.978533},{"timestamp":1332840447,"longitude":-1.567654,"latitude":53.977927}]},"contacts":null}]
这是getHistory函数,在选择联系人之后在表单提交上调用。
function getHistory() {
var contact = $("#contact").val()
var days = $("#days").val()
$.ajax({
type: 'post',
url: 'temp_history.php',
data: {contact: contact, days: days},
context: document.body,
beforeSend: function() {
},
success: function(succ){
var obj = jQuery.parseJSON(succ);
var divs="",tabs="",counts=0;
jQuery("#gMap").gmap3({
action: 'clear'});
jQuery(".marker").remove();
jQuery.each(obj,function(i,item){
tabs +=item.contacts;
if(item.data.latitude != null && item.data.longitude!=null)
{
addMarker(item.name, item.data.timestamp,item.data.latitude,item.data.longitude,item.data.user_id);
}
});
}
});
}
我认为问题是我需要嵌套jQuery.each函数但不确定如何?
addMarker函数是:
function addMarker(name, timestamp, lati, longi, user_id) {
jQuery("#gMap").gmap3({
action: 'addMarkers',
markers:[
{lat:lati, lng:longi, data:name}
]
});
}
谢谢
答案 0 :(得分:1)
你是对的 - 你对JSON的遍历不正确,请在你的success
处理程序中尝试:
success: function(data){
var json = jQuery.parseJSON(data); // If you're returing json, this shouldn't be required
var divs = "", tabs = "", counts = 0;
jQuery("#gMap").gmap3({ action: 'clear' });
jQuery(".marker").remove();
jQuery.each(json, function(i, item) {
var name = item.name;
var userId = item.data.user;
jQuery.each(item.data.data, function(i, nav) {
var ts = nav.timestamp;
var lat = nav.latitude;
var long = nav.longitude;
if (lat != null && long != null) {
addMarker(name, ts, lat, long, userId);
}
});
})
}
此外,值得使JSON中的对象名称更具语义性,尤其是当您在多个级别中列出data
时。