Facebook对象的一部分显示为未定义,但并未定义

时间:2014-10-16 01:32:27

标签: javascript object facebook-javascript-sdk facebook-graph-api-v2.0

我正在处理来自Facebook Javascript SDK的结果,以及"附件"部分对象给了我麻烦。在查看对象时,一切都很好,但是当我尝试在我的网站上显示它时,它说这些属性是未定义的。我解析不正确吗?

这是对象:

{
"id":"xxx_xxx",
"from":{
    "id":"xxxx",
    "name":"User Name"
},
"to":{
    "data":[{
        "name":"Group Name",
        "id":"xxxx"
    }]
},
"picture":"url of image",
"link":"url",
"object_id":"Object ID",
"type":"photo",
"created_time":"2014-10-15T21:09:19+0000",
"updated_time":"2014-10-15T21:09:19+0000",
"attachments":{
    "data":[{
        "media":{
            "image":{
                "height":551,
                "src":"Image Source",
                "width":720
            }
        },
        "target":{
            "id":"742450405803347",
            "url":"target URL"
        },
        "type":"photo",
        "url":"URL"
    }]
}

这是显示"附件"的代码。在网站上的一部分(我知道它很乱,请忽略它):

post_div_html += '<p>------------------</p>\
                <p><b>Media-Image-Source</b>: ' + feed.attachments.data[0] + '</p>\
                <p><b>Target URL</b>: ' + feed.attachments.data[1] + '</p>\
                <p><b>Type</b>: ' + feed.attachments.data[2] + '</p>\
                <p><b>URL</b>: ' + feed.attachments.data[3] + '</p></div>';

现在,为了清楚起见,你看到的结果会导致“未定义”。在我的网站上显示为值。我尝试过的其他所有操作都会导致错误,提示&#39; feed.attachments.data.whatever undefined&#39;。

任何人对我如何展示这些东西都有任何想法?

1 个答案:

答案 0 :(得分:1)

我想你想要的是......

var att = feed.attachments.data[0],
    mediaImageSrc = att.media.image.src,
    targetUrl = att.target.url,
    type = att.type,
    url = att.url;

我希望这是有道理的。

这是一个有效的例子......

&#13;
&#13;
var feed = {
  "id": "xxx_xxx",
  "from": {
    "id": "xxxx",
    "name": "User Name"
  },
  "to": {
    "data": [{
      "name": "Group Name",
      "id": "xxxx"
    }]
  },
  "picture": "url of image",
  "link": "url",
  "object_id": "Object ID",
  "type": "photo",
  "created_time": "2014-10-15T21:09:19+0000",
  "updated_time": "2014-10-15T21:09:19+0000",
  "attachments": {
    "data": [{
      "media": {
        "image": {
          "height": 551,
          "src": "Image Source",
          "width": 720
        }
      },
      "target": {
        "id": "742450405803347",
        "url": "target URL"
      },
      "type": "photo",
      "url": "URL"
    }]
  }
};

var att = feed.attachments.data[0],
  mediaImageSrc = att.media.image.src,
  targetUrl = att.target.url,
  type = att.type,
  url = att.url;

post_div_html = '<p>------------------</p>\
                <p><b>Media-Image-Source</b>: ' + mediaImageSrc + '</p>\
                <p><b>Target URL</b>: ' + targetUrl + '</p>\
                <p><b>Type</b>: ' + type + '</p>\
                <p><b>URL</b>: ' + url + '</p></div>';
document.getElementById('out').innerHTML = post_div_html;
&#13;
<output id="out"></output>
&#13;
&#13;
&#13;