首页 文章

如何在使用Javascript SDK初始登录后使用Facebook API调用

提问于
浏览
3

我刚刚开始将Facebook整合到我目前正在处理的网站上 . 我到目前为止用户可以登录,我可以在登录后获取他们的信息 . 我正在努力理解的是如何在初始登录html页面之后进行FB.api()调用?我知道Javascript SDK会自动处理访问令牌和东西,但我不确定如何使用它 . 到目前为止我所拥有的是:

window.fbAsyncInit = function() 
        {
                FB.init({
                    appId      : 'API_KEY', // Set YOUR APP ID
                    channelUrl : 'DOMAIN', // Channel File
                    status     : true, // check login status
                    cookie     : true, // enable cookies to allow the server to access the session
                    xfbml      : true // parse XFBML
                });

            FB.Event.subscribe('auth.authResponseChange', function(response) 
            {
                console.log("Authorization Change");
                if (response.status === 'connected') 
                {

                    console.log("Connected to FaceBook");
                    //SUCCESS
                }    
                else if (response.status === 'not_authorized') 
                {
                    console.log("Logged into Facebook but not us");
                    FacebookLogin();
                    //FAILED
                } 
                else 
                {
                    console.log("Logged out of both");
                    FacebookLogin();
                    //UNKNOWN ERROR
                }
            }); 
        };   
        function FacebookLogin()
        {
            FB.login(function(response) 
            {
                if (response.authResponse) 
                {
                    window.location = "test.php";
                } 
                else 
                {
                    console.log('User cancelled login or did not fully authorize.');
                }
            },{scope: 'email,user_birthday,read_friendlists'});
        }

        // Load the SDK asynchronously
        (function(d){
            var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
            if (d.getElementById(id)) {return;}
            js = d.createElement('script'); js.id = id; js.async = true;
            js.src = "//connect.facebook.net/en_US/all.js";
            ref.parentNode.insertBefore(js, ref);
        }(document));

所有这些代码都位于登录html页面顶部的脚本标记内 . 我要做的是,一旦用户登录并进行身份验证,我将把他们引导到另一个页面,我将使用FB.api()函数获取他们的信息并填写他们的注册表单 . 有什么建议或提示吗?

1 回答

  • 0

    您可以使用以下函数在用户成功登录后获取有关用户的信息并显示在任何DOM元素中

    function fqlQuery(){
                FB.api('/me', function(response) {
                     var query = FB.Data.query('select name, hometown_location, sex, pic_square from user where uid={0}', response.id);
                     query.wait(function(rows) {
    
                       document.getElementById('name').innerHTML =
                         'Your name: ' + rows[0].name + "
    " + '<img src="' + rows[0].pic_square + '" alt="" />' + "
    "; }); }); }

    更多例子可以找到here

相关问题