AJAX与Facebook身份验证

时间:2011-01-25 14:20:06

标签: javascript ajax facebook

我构建了一个完全基于AJAX的应用程序,它没有页面刷新并使用AJAX加载所有内容。现在我想以一种不会重定向用户以进行页面刷新的方式嵌入facebook身份验证。

目前facebook以这种方式运作:

点击Facebook Connect按钮https://graph.facebook.com/oauth/authorize?client_id=xxxxxxxxxxxxxx&redirect_uri=http://www.xxxxxxxxxx.com/JoinFB.html?&type=user_agent&display=popup&scope=offline_access,publish_stream,sms,email,user_birthday,user_photos,user_photo_video_tags,user_checkins,friends_checkins

,将用户重定向到Facebook

用户操作后,“允许”或“禁止”重定向到http://www.xxxxxxxxxx.com/JoinFB.html,然后我可以使用Javascript来读取用户信息。

问题是我可以使用IFRAME或其他任何方式克服此页面重定向过程吗?

如何在用户允许的情况下检测IFRAME?

1 个答案:

答案 0 :(得分:4)

我会使用JS-SDK,一个完美的例子就是Facebook PHP-SDK example本身:

<?php

require '../src/facebook.php';

$facebook = new Facebook(array(
  'appId'  => '344617158898614',
  'secret' => '6dc8ac871858b34798bc2488200e503d',
));

// See if there is a user from a cookie
$user = $facebook->getUser();

if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me');
  } catch (FacebookApiException $e) {
    echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
    $user = null;
  }
}

?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
  <body>
    <?php if ($user) { ?>
      Your user profile is
      <pre>
        <?php print htmlspecialchars(print_r($user_profile, true)) ?>
      </pre>
    <?php } else { ?>
      <fb:login-button></fb:login-button>
    <?php } ?>
    <div id="fb-root"></div>
    <script>
      window.fbAsyncInit = function() {
        FB.init({
          appId: '<?php echo $facebook->getAppID() ?>',
          cookie: true,
          xfbml: true,
          oauth: true
        });
        FB.Event.subscribe('auth.login', function(response) {
          window.location.reload();
        });
        FB.Event.subscribe('auth.logout', function(response) {
          window.location.reload();
        });
      };
      (function() {
        var e = document.createElement('script'); e.async = true;
        e.src = document.location.protocol +
          '//connect.facebook.net/en_US/all.js';
        document.getElementById('fb-root').appendChild(e);
      }());
    </script>
  </body>
</html>

现在点击fb:login-button

<fb:login-button scope="offline_access,publish_stream,sms,email,user_birthday,user_photos,user_photo_video_tags,user_checkins,friends_checkins"></fb:login-button>

将打开facebook弹出窗口,在授权过程后弹出窗口将自动关闭并触发auth.login事件,我会将重新加载方法window.location.reload();更改为ajax调用做你正在做的事情。