使用ajax / php动态加载Facebook JS sdk登录

时间:2013-07-19 06:28:57

标签: jquery ajax facebook facebook-javascript-sdk

我可以在没有sdk的情况下使用Facebook JS SDK执行登录和获取数据。但是我希望它能用ajax做。

<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>

粗体部分正在执行加载动作。我想如果用ajax完成那么我就完成了。

我尝试使用ajax google jquery api,但是在登录完成后再次加载整个页面:

<?php
session_start();
include_once("config.php");

if(isset($_GET["logout"]) && $_GET["logout"]==1)
{
//User clicked logout button, distroy all session variables.
session_destroy();
header('Location: '.$return_url);
}
?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml" xml:lang="en-gb" lang="en-gb" >
<head>
<!-- Call jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<title>Ajax Facebook Connect With jQuery</title>
 <script>
 function AjaxResponse()
 {
     var myData = 'connect=1'; //For demo, we will pass a post variable, Check process_facebook.php
     jQuery.ajax({
     type: "POST",
     url: "process_facebook.php",
     dataType:"html",
     data:myData,
     success:function(response){
     $("#results").html('<fieldset style="padding:20px">'+response+'</fieldset>'); //Result
 },
     error:function (xhr, ajaxOptions, thrownError){
     $("#results").html('<fieldset style="padding:20px;color:red;">'+thrownError+'</fieldset>'); //Error
    }
 });
 }

function LodingAnimate() //Show loading Image
{
    $("#LoginButton").hide(); //hide login button once user authorize the application
    $("#results").html('<img src="ajax-loader.gif" /> Please Wait Connecting...'); //show loading image while we process user
}

function ResetAnimate() //Reset User button
{
    $("#LoginButton").show(); //Show login button
    $("#results").html(''); //reset element html
}

 </script>
</head>
<body>
<?php
if(!isset($_SESSION['logged_in']))
{
?>
    <div id="results">
    </div>
    <div id="LoginButton">
    <div class="fb-login-button" onlogin="javascript:CallAfterLogin();" size="medium" scope="<?php echo $fbPermissions; ?>">Connect With Facebook</div>
    </div>
<?php
}
else
{
    echo 'Hi '. $_SESSION['user_name'].'! You are Logged in to facebook, <a href="?logout=1">Log Out</a>.';
}
?>

<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: '<?php echo $appId; ?>',cookie: true,xfbml: true,channelUrl: '<?php echo $return_url; ?>channel.php',oauth: true});};
(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);}());

function CallAfterLogin(){
        FB.login(function(response) {
        if (response.status === "connected")
        {
            LodingAnimate(); //Animate login
            FB.api('/me', function(data) {
              if(data.email == null)
              {
                    //Facbeook user email is empty, you can check something like this.
                    alert("You must allow us to access your email id!");
                    ResetAnimate();

              }else{
                    AjaxResponse();
              }
          });
         }
    });
}

</script>

</body>
</html>

1 个答案:

答案 0 :(得分:-2)

以下是完整的工作示例:

             ThenWat                                                               http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">         
                     。中间{                 背景颜色:黄色;             }

        .left{
            background-color:Green;
        }
        .url{
            box-sizing: border-box;
            display: block;
        }
        .url:hover {
            box-shadow: 2px 2px 5px rgba(0,0,0,.2);
        }
        .header{
            background-color: #61B329;
            color: #FFF;
            margin-top: 0px !important;
            margin-bottom: 20px;
            padding-bottom: 9px;
        }
        .page-header-text {
            padding-left: 15px;
            padding-top: 20px;
            padding-bottom: 10px;
            margin: 0px;
        }


        html, body { margin: 0; padding: 0; border: 0 }
    </style>
    <script>
        $( document ).ready(function()
        {
            console.log( "ready!" );
            //alert("Welcome");
        });
    </script>
</head>

<body>
    <div class="page-header header">
        <h1 class="page-header-text">thenWat</h1>
    </div>      
        <table border = "0" width = "100%">
            <tr>
                <div class = "middle">
                    <td style = "width:40%">
                    <input type = "button" id = "loginButton" class = "btn btn-primary" onclick = "authUser();" value = "Login | ThenWat" style = "display:none; left:500px; margin-top:200px; position:relative"/> 
                    </td>               
                </div>
            </tr>               
        </table>
    <div id = "fb-root"></div>
    <script type = "text/javascript">
        var userid;
        FB.init({
        //appId: '',
        appId: 'app id',
        xfbml: true,
        status: true,
        cookie: true,
        });
        FB.getLoginStatus(checkLoginStatus);
        function authUser() 
        {
            FB.login(checkLoginStatus, {scope:'email'});
        }
        function checkLoginStatus(response) 
        {               
            if(response && response.status == 'connected') 
            {
            FB.api('/me?fields = movies,email,name,gender,locale,location,link', function(mydata)
            {
                console.log(mydata.email);
                console.log(mydata.id);
                userid = mydata.id;
                var name = mydata.name;
                gender = mydata.gender;
                locale = mydata.locale;
                city = mydata.location;
                link = mydata.link;
                //alert(name);
                var email = mydata.email;
                //var json = JSON.stringify(mydata.movies.data);
                //var a = JSON.parse(json);
                var picture = "https://graph.facebook.com/"+userid+"/picture?type = small";
                // alert(picture);
                $.post('user_record.php',{ name: name, email: email, userid:userid, picture:picture, gender: gender, locale: locale, city: city, link: link}, function(data)
                {
                    var $form = $("<form id = 'form1' method = 'post' action = 'start.php'></form>");
                    $form.append('<input type = "hidden" name = "userid" value = "'+userid+'" />');
                    $('body').append($form);
                    window.form1.submit();
                });
            });

            console.log('Access Token: ' + response.authResponse.accessToken);
            }
            else
            {
                document.getElementById('loginButton').style.display = 'block';
            }
        }
    </script>   
</body>