仅在登录时调用函数

时间:2016-03-11 13:47:59

标签: javascript php facebook

我尝试使用Facebook JavaScript SDK和PHP实现登录,因此当用户成功登录时,会发送一个AJAX请求来设置$ _SESSION。首先,我使用了docs中的示例代码,但这只是循环发送AJAX请求的函数,只有在用户第一次登录时才能获取。

function statusChangeCallback(response) {
    if (response.status === 'connected') {
        login_FBAuth();
    } else if (response.status === 'not_authorized') {
        document.getElementById('status').innerHTML = 'Please log ' +
                'into this app.';
    } else {
        document.getElementById('status').innerHTML = 'Please log ' +
                'into Facebook.';
    }
}

function checkLoginState() {
    FB.getLoginStatus(function (response) {
        statusChangeCallback(response);
    });
}

window.fbAsyncInit = function () {
    FB.init({
        appId: 'secret',
        cookie: true,
        xfbml: true,
        version: 'v2.5'
    });
    FB.getLoginStatus(function (response) {
        statusChangeCallback(response);
    });
};

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

function login_FBAuth() {
    FB.api('/me', function (response) {
        $.ajax({
            url: 'auth/fb_login.php',
            method: 'POST',
            data: {action: 'login', nombre: response.name},
            success: function (server_response) {
                console.log("Me fui y encontre el servidor");
                console.log("El servidor responde" + server_response);
                if (server_response === 'ok') {
                    console.log('Respuesta correcta');
                    window.location.href = "appmenu.php";
                }
            },
            error: function () {
                console.log("Error en respuesta servidor");
            }
        });
    });
}

HTML

<fb:login-button scope="public_profile, email, user_posts, publish_actions" onlogin="checkLoginState();"></fb:login-button>
<div id="status"></div>

0 个答案:

没有答案