简体   繁体   English

使用 JQuery 解析嵌套的 JSON

[英]Parse Nested JSON With JQuery

I'm new to JSON and really struggling with this.我是 JSON 的新手,我真的很挣扎。 I've read countless other posts and web pages but can't seem to figure it out.我已经阅读了无数其他帖子和 web 页面,但似乎无法弄清楚。

I'm using PHP to output JSON (from data from the database) with this code:我正在使用 PHP 到 output JSON (来自数据库中的数据)与此代码:

    header('Content-type: application/json');
    echo json_encode($data);

Here is the JSON:这是 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
    }
}

I think the problem I'm having is that the JSON is nested(might be wrong there)?.我认为我遇到的问题是 JSON 是嵌套的(那里可能是错误的)?

This is the JQuery:这是 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++;
        });
    });
}

Any ideas or suggestions appreciated!任何想法或建议表示赞赏!

Thanks!谢谢!

i think that the problem is that you call $.each on json.results (if the json is exactly what you showed us).我认为问题在于您在 json.results 上调用 $.each(如果 json 正是您向我们展示的内容)。

you sholud do:你应该这样做:

    $.each(json,function(i,profile){
       $("#profiles").append('<p><img src="'+profile.image+'" widt="48" height="48" />'+profile.name+'</p>');
    });

look at the fiddle here: http://jsfiddle.net/ENcVd/1/ (it alerst the image property of you json object)看看这里的小提琴: http://jsfiddle.net/ENcVd/1/ (它会提醒您 json 对象的图像属性)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM