0

我已经为此苦苦挣扎了好几个小时...

我的网站上有一个使用 Facebook 登录按钮,我正在尝试将经过身份验证的用户数据添加到数据库中。希望也许一双新的眼睛能发现我的错误,所以这就是我所拥有的。

<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
    FB.init({
        appId   : 'MY APP ID',
        oauth   : true,
        status  : true, // check login status
        cookie  : true, // enable cookies to allow the server to access the session
        xfbml   : true // parse XFBML
    });

  };

function fb_login(){
    FB.login(function(response) {

        if (response.authResponse) {
            console.log('Welcome!  Fetching your information.... ');
            //console.log(response); // dump complete info
            access_token = response.authResponse.accessToken; //get access token
            user_id = response.authResponse.userID; //get FB UID

            FB.api('/me', function(response) {
                 $.post("addtodb.php", {name: response.name})
            });

            window.location.href = "next.php"; //redirect once authorized

            FB.api('/me/devlogintest:join', 'action', 
            { object : 'http://www.mysite.com' });

        } else {
            //user hit cancel button
            console.log('User cancelled login or did not fully authorize.');

        }
    }, {
        scope: 'email,publish_actions'
    }
    );
}
(function() {
    var e = document.createElement('script');
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    e.async = true;
    document.getElementById('fb-root').appendChild(e);
}());
</script>

addtodb.php 脚本...

<?php

include('config.php');
$fbname = $_POST['name'];

if(!empty($_POST)){ //won't submit blanks if no data

// Make a MySQL Connection
mysql_connect($Host,$Username,$Password) or die(mysql_error());
mysql_select_db($Database) or die(mysql_error());

// Insert rows
mysql_query("INSERT INTO fbusers 
(name) VALUES('$fbname') ") 
or die(mysql_error());  
}
?>

我似乎无法让用户的姓名发布并添加到数据库中。如果我在 javascript 上使用警报,它会弹出正确的信息。当我启用错误检查时,php 脚本端似乎也没有任何错误。

Jquery 调用包含在 head 标签中。

我错过了什么?

4

1 回答 1

2

代码中的主要问题之一是在运行异步代码之后使用重定向......FB.api$.post以异步方式工作,因此重定向next.php可能在FB.api返回数据和/或$.post提交数据到服务器之前发生。

正如评论中所说,将发出未定义$results = mysql_query($query) or die("Error: " . mysql_error());的警告并导致空查询。$query如果调用了脚本(可能没有),您应该在日志中看到该警告(启用错误报告)。

尝试在回调函数中移动重定向代码,$.post这样它就会等到您的脚本收到数据。

于 2012-05-06T07:17:13.497 回答