【问题标题】:Parse Nested JSON With JQuery使用 JQuery 解析嵌套的 JSON
【发布时间】:2011-07-01 12:16:38
【问题描述】:

我是 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++;
        });
    });
}

任何想法或建议表示赞赏!

谢谢!

【问题讨论】:

  • 你的 JSON 看起来像这样吗?我期待一个数组......它真的有一个叫做“结果”的根键吗?
  • JSON 文件的顶层可以是对象或数组。
  • 是的,这是 PHP 的 JSON 输出。关于 .results 的好点 - 在那里复制和粘贴错误。

标签: php javascript jquery json


【解决方案1】:

我认为问题在于您在 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 对象的图像属性)

【讨论】:

  • 感谢您的回答 - 该示例完美运行。我认为我的问题可能出在我从中提取 JSON 的 URL 上。它显示在浏览器中,但使用 jsfiddle 代码它只是提醒未定义?
  • 同样在 Firebug 控制台中,GET url 是红色的,但是有 200 OK 服务器响应?
  • 可能问题是您发出请求的服务器不在发出请求的页面的同一域中。是这样吗?无论如何,如果你有一个完整的小提琴,我会尽力帮助!
  • 啊,没错,我正在 PhoneGap 中构建一个应用程序(本地运行的 js 脚本),它从另一台服务器获取 url。这不能做吗?再次感谢。
  • 我认为您必须使用 $.ajax() 并将 crossDomain 选项设置为 true。看这里api.jquery.com/jQuery.ajax
猜你喜欢
  • 2015-06-15
  • 2020-04-26
  • 1970-01-01
  • 2019-08-20
  • 2015-08-28
  • 2017-08-03
  • 2018-10-06
  • 2013-03-28
  • 1970-01-01
相关资源
最近更新 更多