未捕获的TypeError:无法读取属性' name'未定义的图谱API [2.5]

时间:2016-02-11 07:35:53

标签: javascript facebook facebook-graph-api facebook-javascript-sdk

我使用Facebook Graph API进行2次API调用。第一个API调用返回使用相同Web应用程序的朋友列表,第二个API调用返回登录用户的公共信息。我在包含第一个API调用的函数的 for循环 中遇到问题。每当我尝试读取响应中的数据时,我都会收到错误..

Uncaught TypeError: Cannot read property 'name' of undefined

我的JavaScript SDK代码 ..

        function facebookSignIn() {

        FB.login(function(response) {
            // handle the response
            console.log("Response goes here!");

            // retrieve the list of friends to whom message was sent
            FB.api(
                '/me/friends', function (response) {
                    if (response && !response.error) {
                        /* handle the result */
                        console.log("Response for /me/friends goes here!");
                        console.log(JSON.stringify(response.data));
                        console.log(JSON.stringify(response.data[0].name));
                        for(var i =0;i<=response.data.length;i++){
                            var friend_name = response.data[i].name;
                            var friend_id= response.data[i].id+"@fb";                       
                            addFriendSetValues(friend_name, '-', friend_id, loginemail);
                            addFriendDbCreate();
                        }
                    }
                }
            );

            FB.api('/me?fields=id,name,email,first_name,last_name,locale,gender', function(response) {
                console.log('Successful login for: ' + response.name+" "+response.id+" "+response.email);
                loginpassword = response.id;
                loginemail =  response.email;

                loginDbCreate();    //this function is in the script_admin_v2.js
            });

        }, {scope: 'email,public_profile,user_friends'});            
    }

控制台输出 ..

    Response for /me/friends goes here!
    [{"name":"Friend A","id":"10153492155956028"},{"name":"Friend B","id":"117431545310469"}]
   "Friend A"
    Successful login for: Lucy 951425764944314 lucy@abc.com
    all.js:86 Uncaught TypeError: Cannot read property 'name' of undefined

即使我能够打印 response.data [0] .name)的值,当我用for循环中的i 替换零时 ,我得到了Uncaught Error..Any想法我哪里出错?

1 个答案:

答案 0 :(得分:1)

我认为,你需要改变

for(var i =0;i<=response.data.length;i++){
      var friend_name = response.data[i].name;
      var friend_id= response.data[i].id+"@fb";
      addFriendSetValues(friend_name, '-', friend_id, loginemail);
      addFriendDbCreate();
 }

 for(var i =0;i<=response.data.length;i++){
      if (response.data.hasOwnProperty(i)) {
        var friend_name = response.data[i].name;
        var friend_id = response.data[i].id + "@fb";
        addFriendSetValues(friend_name, '-', friend_id, loginemail);
        addFriendDbCreate();
      }
    }