[英]Parse Nested JSON With JQuery
我是 JSON 的新手,我真的很掙扎。 我已經閱讀了無數其他帖子和 web 頁面,但似乎無法弄清楚。
我正在使用 PHP 到 output 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++;
});
});
}
任何想法或建議表示贊賞!
謝謝!
我認為問題在於您在 json.results 上調用 $.each(如果 json 正是您向我們展示的內容)。
你應該這樣做:
$.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 對象的圖像屬性)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.