Parse Nested JSON With JQuery
我是JSON的新手,真的很为此苦苦挣扎。我已经阅读了无数其他文章和网页,但似乎无法弄清楚。
我正在使用PHP通过以下代码输出JSON(来自数据库中的数据):
1 2 |
这是JSON:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | { "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:
1 2 3 4 5 6 7 8 9 10 11 12 | 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正是您向我们展示的内容)。
您应该这样做:
1 2 3 | $.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属性)