我是JSON的新手并且真的很挣扎。我已经阅读了无数其他帖子和网页,但似乎无法弄明白。
我正在使用PHP通过以下代码输出JSON(来自数据库中的数据):
header('Content-type: application/json');
echo json_encode($data);
这是JSON:
{
"x0": {
"id": "1",
"name": "Rob",
"online": "1",
"gender": "m",
"age": "29",
"height": "5'8''",
"build": "Average",
"ethnicity": "White",
"description": "Art geek person",
"looking_for": "Anything",
"image": "4fs5d43f5s4d3f544sdf.jpg",
"last_active": "29-06-11-1810",
"town": "Manchester",
"country": "UK",
"distance": 0.050973560712308
},
"x1": {
"id": "2",
"name": "Dave",
"online": "1",
"gender": "m",
"age": "29",
"height": "5'8''",
"build": "Average",
"ethnicity": "White",
"description": "Art geek person",
"looking_for": "Anything",
"image": "4fs5d43f5s4d3f544sdf.jpg",
"last_active": "29-06-11-1810",
"town": "Manchester",
"country": "UK",
"distance": 0.050973560712308
}
}
我认为我遇到的问题是JSON是嵌套的(可能是错误的)?
这是JQuery:
function fetchProfiles() {
var url='http://url.com/here';
var i = 0;
var handle = 'x'.i;
$.getJSON(url,function(json){
$.each(json.results,function(i,profile){
$("#profiles").append('<p><img src="'+profile.handle.image+'" widt="48" height="48" />'+profile.handle.name+'</p>');
i++;
});
});
}
赞赏任何想法或建议!
谢谢!
答案 0 :(得分:3)
我认为问题是你在json.results上调用$ .each(如果json正是你向我们展示的那样)。
你sholud做:
$.each(json,function(i,profile){
$("#profiles").append('<p><img src="'+profile.image+'" widt="48" height="48" />'+profile.name+'</p>');
});
看看这里的小提琴:http://jsfiddle.net/ENcVd/1/(它是你json对象的image属性)