如何从FB.api返回的对象中读取属性数据?

时间:2011-06-04 02:46:44

标签: facebook facebook-graph-api

我有以下代码工具来捕获用户发表评论时的事件。它正在正确触发,但问题是我不知道如何解析传递给我的回调函数的对象。

<script>
    window.fbAsyncInit = function () {
        FB.init({ appId: '<myAppId>', status: true, cookie: true, xfbml: true });
        FB.Event.subscribe('comment.create', function () {
            FB.api('/comments/?ids=http://foo.com', function (response) {
                console.log(response);
            });
        });
    };
    (function () {
        var e = document.createElement('script'); e.async = true;
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        document.getElementById('fb-root').appendChild(e);
    } ());
</script>

查看firebug中的控制台日志,console.log(response)显示此对象:

{
    "http://foo.com": {
       "data": [
          {
             "id": "10150090820621770_15631060",
             "from": {
                "name": "Test User",
                "id": "1234455"
             },
             "message": "testing",
             "created_time": "2011-04-18T01:55:38+0000"
          },
          {
             "id": "10150090820621770_15631066",
             "from": {
                "name": "Test UserToo",
                "id": "1149043581"
             },
             "message": "testing2",
             "created_time": "2011-04-18T01:56:12+0000"
          }
       ]
    }
 }

但是,如果我尝试使用response.data[0].from.name访问该对象,则会返回undefined。此外,以下所有内容还会返回undefined

  • response.data
  • response.data.length
  • response.data[0]

我不知道如何解析对象来读取属性。有人有任何提示吗?

3 个答案:

答案 0 :(得分:2)

你忘了你的“http://foo.com”.. 所以它应该像response["http://foo.com"].data[0].idresponse["http://foo.com"].data[0].from.name

答案 1 :(得分:0)

我认为答案是文字。您需要让编译器将文本解析为javascript对象。由于文本格式为JSON,这很容易。在支持JSON的浏览器上(维基百科页面说:ff 3.5 +,IE8 +,opera 10.5+,基于webkit的东西),您可以执行以下操作:

var responseObject = JSON.parse(response);

应该能得到你想要的对象。

答案 2 :(得分:0)

我使用FQL来访问FB评论。

相关问题