如何从FB.api返回的对象读取属性数据?
问题描述:
我有以下代码实现以在用户离开评论时捕获事件。它是正确的解雇,但问题是我不知道如何解析传递给我的回调函数的对象。如何从FB.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>
查看控制台日志中的萤火虫,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]
我不知道如何解析读取属性的对象。任何人有任何提示?
答
你忘了你的“http://foo.com” .. 所以应该像response["http://foo.com"].data[0].id
或者response["http://foo.com"].data[0].from.name
答
我想响应文本。您需要让编译器将文本解析为JavaScript对象。因为文本被格式化为JSON,这很容易。在支持JSON的浏览器(*页面称:FF 3.5+,IE8 +,1050 +歌剧,基于WebKit的东西),你可以做到以下几点:
var responseObject = JSON.parse(response);
应该得到你想要的对象。
请做更多解释 – johannes 2012-10-26 21:22:37