Facebook的API和放大器; Ajax的POST请求 [英] Facebook API & Ajax POST request

查看:154
本文介绍了Facebook的API和放大器; Ajax的POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Facebook连接/断开链接。当用户点击连接Facebook链接(在的index.php ),它会检查用户状态(他是连接到Facebook或不呢?),那么如果他不接,我的脚本发送Ajax $ 。员额要求为将connect.php ,以便检索数据库的相关信息(如:是在我们的数据库中注册的用户?)。在此之后,它发回给index.php的一个回应:如果没有错误,页面刷新。在这种情况下,如果一切正常,之后页面是由脚本( window.location.reload(); )刷新,我们应该看到的Facebook用户ID(UID)

问题是UID仍然是空后的页面通过Ajax回调重新加载。但是,如果我刷新页面手动一次,我现在看到的UID。

我测试很多方面来理解这个问题的来源,我发现有一个问题,这个Facebook的要求: $我= $ facebook-> API('/我');

不管怎样,我不能没有的 $我= $ facebook-> API('/我'); ,所以如果你想测试我的剧本,发现问题,这里就是你需要 ! (不要忘了最后的Facebook SDK); - )

任何帮助将是非常一个preciated!谢谢!

的index.php

 <!DOCTYPE HTML PUBLIC -  // W3C // DTD XHTML 1.0过渡// ENhttp://www.w3.org/TR/xhtml1/DTD/ XHTML1-transitional.dtd>
< HTML的xmlns =htt​​p://www.w3.org/1999/xhtml>
< HEAD>
< META HTTP-当量=Content-Type的CONTENT =text / html的;字符集= UTF-8/>
<冠军> Facebook连接< /标题>
<脚本SRC =JS / jquery.js和>< / SCRIPT>
< PHP

/ * Facebook应用程序配置* /
$的appid ='YOU_APP_ID';
$ appSecret ='YOUR_APP_SECRET';

定义(APPID,$ APPID);
定义(APPSECRET,$ appSecret);

/ * API调用* /
如果(!class_exists('FacebookApiException'))
{
  require_once('INC / facebook.php');
}

$ = Facebook的新的Facebook(阵列(
   '的appid => APPID,
   秘密=> APPSECRET,
));

$ fb_user = $ facebook->的getUser();

如果($ fb_user){
    尝试
    {
       $我= $ facebook-> API(/我);
       $ UID = $ facebook->的getUser();
    }
      赶上(FacebookApiException $ E)
    {
       //回声error_log中($ E);
       $ fb_user = NULL;
    }
}
?>
< /头>

<身体GT;
< D​​IV ID =FB-根>< / DIV>
<脚本>(功能(D,S,ID){
  变种的js,FJS = d.getElementsByTagName(多个)[0];
  如果(d.getElementById(ID))回报;
  JS = d.createElement(S); js.id = ID;
  js.src =//connect.facebook.net/fr_FR/all.js#xfbml=1&appId=<?=APPID?>;
  fjs.parentNode.insertBefore(JS,FJS);
}(文档,脚本,Facebook的jssdk'));&LT; / SCRIPT&GT;

&LT;脚本类型=文/ JavaScript的&GT;
    window.fbAsyncInit =功能(){
        FB.init({
            APPID:'?&LT; = APPID&GT;',
            OAuth的:真正的,
            状态:真正的,
            饼干:真正的,
            XFBML:真
        });
    };

    功能fb_connect(){
        警报('FB.getLoginStatus');
        FB.getLoginStatus(函数(响应){
            如果(response.status ==='连接'){
                VAR access_token = response.authResponse.accessToken;
                VAR USER_ID = response.authResponse.userID;
                //
                window.location.reload();
                //
            } 其他 {
                警报('FB.login');
                FB.login(函数(响应){
                    VAR access_token = response.authResponse.accessToken;
                    VAR USER_ID = response.authResponse.userID;
                        .post的$('将connect.php',功能(数据){
                        变种物镜= $ .parseJSON(数据);
                        如果(OBJ ['错误'] == 0){
                            警报(OBJ ['消息']);
                            window.location.reload();
                        } 其他 {
                            警报(OBJ ['消息']);
                        }
                    });
                    //

                },{
                    适用范围:电子邮件,publish_stream,user_birthday
                });
            }
        });
    }

    功能fb_logout(){
        FB.logout(函数(响应){
            window.location.reload();
        });
    }

    (功能() {
      变种E = document.createElement方法(脚本);
      e.src = document.location.protocol +'//connect.facebook.net/fr_FR/all.js;
      e.async = TRUE;
      的document.getElementById('FB-根)的appendChild(E)。
    }());
&LT; / SCRIPT&GT;
&其中p为H.; UID:?&其中; = $ fb_user&GT;&所述; / P&GT;
&LT;?如果PHP($ fb_user){&GT;
&LT; A HREF =#的onclick =fb_logout();&GT;断开连接和LT; / A&GT;
&LT; PHP}其他{&GT?;
&LT; A HREF =#的onclick =fb_connect();&GT;连接Facebook&LT; / A&GT;
&LT; PHP}&GT?;
&LT; /身体GT;
&LT; / HTML&GT;
 

将connect.php

 &LT; PHP
/ * Facebook应用程序配置* /
$的appid ='YOUR_APP_ID';
$ appSecret ='YOUR_APP_SECRET';

定义(APPID,$ APPID);
定义(APPSECRET,$ appSecret);

/ * API调用* /
如果(!class_exists('FacebookApiException'))
{
  require_once('INC / facebook.php');
}

$ = Facebook的新的Facebook(阵列(
   '的appid =&GT; APPID,
   秘密=&GT; APPSECRET,
));

$ fb_user = $ facebook-&GT;的getUser();

如果($ fb_user){
    尝试
    {
       $我= $ facebook-&GT; API(/我);
       $ UID = $ facebook-&GT;的getUser();
    }
      赶上(FacebookApiException $ E)
    {
       //回声error_log中($ E);
       $ fb_user = NULL;
    }
}

/* 回电话 */
$结果=阵列();

如果($ fb_user){
    $结果['错误'] = 0;
    $结果[信息] = $我[如first_name']。
} 其他 {
    $结果['错误'] = 1;
    $结果[信息] ='错误';
}

回声json_en code($结果);
?&GT;
 

解决方案
  

抱歉,但它不是多余的,我真的需要它来检查的东西在数据库中。事实上,如果用户没有在数据库中注册的用户将被重定向到另一个页面,而不是重新加载索引页面

所以,我怀疑,没有真正的需要AJAX调用。

您也可以同样刷新你的的index.php ,做你的数据库检查那里,然后要么放出来的内容为成功登录的用户,或重定向他们有使用的位置的头。

  

不管怎样,我需要了解我为什么不能动态地重新加载,而不是手动检索我的FB的相关信息。这是真正的问题。

那么,你应该调查你的真正的问题:调试异常,你可能会得到,或检查有什么不同使用额外的AJAX一步都在登录流程或避免它(如得到什么饼干设置时,他们得到发回的下一个请求,等等。)

I have a Facebook connect/disconnect link. When user clicks on "Facebook connect" link (on index.php), it checks the user state (Is he connected to Facebook or not?) then if he's not connected, my script sends an Ajax $.post request to connect.php in order to retrieve infos from database (for instance : Is the user registered in our database?). After that, it sends back a response to index.php : if there is no error, the page is refreshed. In this case, if everything is ok, after the page is refreshed by the script (window.location.reload();), we should see the Facebook user ID (UID).

The problem is the UID is still empty after the page is reloaded through the ajax callback. But, if I refresh the page manually one more time, I can now see the UID.

I test many ways to understand where the problem comes from, and I found there is a problem with this Facebook request : $me = $facebook->api('/me');

Anyway, I can't do without $me = $facebook->api('/me'); so if you want to test my script and find the problem, here is what you need ! (don't forget the last Facebook SDK) ;-)

Any help would be very apreciated ! Thanks !

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Facebook Connect</title>
<script src="js/jquery.js"></script>
<?php

/* FACEBOOK APP CONFIGURATION */
$appId = 'YOU_APP_ID';
$appSecret = 'YOUR_APP_SECRET';

define("APPID",$appId);
define("APPSECRET",$appSecret);

/* API CALL */
if (!class_exists('FacebookApiException'))
{
  require_once('inc/facebook.php' );
}

$facebook = new Facebook(array(
   'appId' => APPID,
   'secret' => APPSECRET,
));

$fb_user = $facebook->getUser();

if ($fb_user) {
    try
    {
       $me = $facebook->api('/me');
       $uid = $facebook->getUser();
    }
      catch (FacebookApiException $e)
    {
       //echo error_log($e);
       $fb_user = null;
    }
}
?>
</head>

<body>
<div id="fb-root"></div>
<script>(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/fr_FR/all.js#xfbml=1&appId=<?=APPID?>";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

<script type="text/javascript">
    window.fbAsyncInit = function() {
        FB.init({
            appId   : '<?=APPID?>',
            oauth   : true,
            status  : true,
            cookie  : true,
            xfbml   : true
        });
    };

    function fb_connect() {
        alert('FB.getLoginStatus');
        FB.getLoginStatus(function(response) {
            if (response.status === 'connected') {
                var access_token = response.authResponse.accessToken;
                var user_id = response.authResponse.userID;
                //
                window.location.reload();
                //
            } else {
                alert('FB.login');
                FB.login(function(response) {
                    var access_token = response.authResponse.accessToken;
                    var user_id = response.authResponse.userID;
                        $.post('connect.php', function(data) {
                        var obj = $.parseJSON(data);
                        if (obj['error']==0) {
                            alert(obj['message']);
                            window.location.reload();
                        } else {
                            alert(obj['message']);
                        }
                    });
                    //

                }, {
                    scope: 'email, publish_stream, user_birthday'
                });
            }
        });
    }

    function fb_logout() {
        FB.logout(function(response) {
            window.location.reload();
        }); 
    }

    (function() {
      var e = document.createElement('script');
      e.src = document.location.protocol + '//connect.facebook.net/fr_FR/all.js';
      e.async = true;
      document.getElementById('fb-root').appendChild(e);
    }());
</script>
<p>UID : <?=$fb_user?></p>
<?php if ($fb_user) { ?>
<a href="#" onclick="fb_logout();">Disconnect</a>
<?php } else { ?>
<a href="#" onclick="fb_connect();">Facebook connect</a>
<?php } ?>
</body>
</html>

connect.php

<?php
/* FACEBOOK APP CONFIGURATION */
$appId = 'YOUR_APP_ID';
$appSecret = 'YOUR_APP_SECRET';

define("APPID",$appId);
define("APPSECRET",$appSecret);

/* API CALL */
if (!class_exists('FacebookApiException'))
{
  require_once('inc/facebook.php' );
}

$facebook = new Facebook(array(
   'appId' => APPID,
   'secret' => APPSECRET,
));

$fb_user = $facebook->getUser();

if ($fb_user) {
    try
    {
       $me = $facebook->api('/me');
       $uid = $facebook->getUser();
    }
      catch (FacebookApiException $e)
    {
       //echo error_log($e);
       $fb_user = null;
    }
}

/* CALLBACK */
$result = array();

if ($fb_user) {
    $result['error'] = 0;
    $result['message'] = $me['first_name'];;
} else {
    $result['error'] = 1;
    $result['message'] = 'error';
}

echo json_encode($result);
?>

解决方案

Sorry, but it's not superfluous, I really need it to check things in database. In fact, if the user is not registered in database, the user is redirected to another page instead reloading the index page

So, as I suspected, no real need for the AJAX call.

You could just as well reload your index.php, do your database checks there, and then either put out content for a successfully logged in user, or redirect them from there using a Location header.

Anyway, I need to understand why I can't retrieve my FB infos by reloading dynamically instead manually. This is the real problem.

Well then you should investigate your real problem: Debug the exception you might be getting, or check what differences there are in the login flow using that extra AJAX step or avoiding it (like what cookies get set when, do they get send back with the next request, etc.)

这篇关于Facebook的API和放大器; Ajax的POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆