FB.api仅在第一次AJAX调用页面时加载

时间:2012-06-25 05:47:14

标签: javascript ajax facebook sdk

我遇到FB.api的问题,仅在第一次通过AJAX检索页面时加载。 FB.getLoginStatus确实可以工作。

演示页面:http://proof.ptly.com/test/fb/test-ajax.htm(点击加载链接第一次工作,但第二次单击时失败)

预期/所需行为:在向应用授予权限后,应该列出与用户关联的所有群组或网页

当前行为:组列表仅在首次加载时填充。后续点击不加载列表(FB.api不返回响应 - 用于记录的视图控制台)

这个问题背后的原因是我检索的页面(test.htm)无法更改,但我从(test-ajax.htm)调用它的页面可以。虽然我知道这种方法并不理想,但我想知道是否有可能克服这种方法。因此,改变基础test.htm的建议虽然正确,但不能解决我遇到的问题。

示例代码

调用AJAX页面的主页

<html>
    <head>
        <title>My Facebook Login Page</title>
        <script type="text/javascript" language="javascript" src="js/jquery.js"></script>
        <script>
        var loaded = false;
        jQuery(document).ready(function(){
            jQuery("#lnk").click(function(e){
                e.preventDefault();
                jQuery("#divContent").load("test.htm", function(){
                    if(loaded)
                    {

                        FB.getLoginStatus(FBverifyLogin);
                    }
                    else
                    {

                        loaded = true;
                    }
                });
            });
        });
        </script>
    </head>
    <body>
        <a href="#" id='lnk'>load</a>
        <div id='divContent'></div>
    </body>
 </html>

正在检索AJAX页面

    <script type="text/javascript">
        var FB_config = {
            API_ID: "347798778614308",
            PERMISSIONS: "publish_stream,manage_pages,user_groups",
        };
        (function(d){
           var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
           js = d.createElement('script'); js.id = id; js.async = true;
           js.src = "//connect.facebook.net/en_US/all.js";
           d.getElementsByTagName('head')[0].appendChild(js);
         }(document));


        jQuery(document).ready(function(){
            // initialise FB
            window.fbAsyncInit = function() {
                FB.init({
                    appId      : '347798778614308',
                    status     : true, 
                    cookie     : true,
                    xfbml      : true,
                    oauth      : true
                });
                FB.Event.subscribe('auth.statusChange', FBverifyLogin);
            };
        });


        function FBverifyLogin(response) {
            console.log("FBverifyLogin");
            console.log(response);
            jQuery("#FBreauth").hide();
            if (response.status === 'connected') {
                // the user is logged in and has authenticated your
                // app, and response.authResponse supplies
                // the user's ID, a valid access token, a signed
                // request, and the time the access token 
                // and signed request each expire
                var uid = response.authResponse.userID;
                var accessToken = response.authResponse.accessToken;
                ShowPostToFacebookCheckbox();
                FBdisplayMyPages(response.authResponse);
                jQuery("#btnLogin").hide();
                checkPermissions();

            } else if (response.status === 'not_authorized') {

            } else {
                // the user isn't logged in to Facebook.
                jQuery("#btnLogin").show();
                return false;
            }
        }
        function checkPermissions(){
            console.log("checkPermissions");
            FB.api('/me/permissions', function(response) {
                console.log("in checkPermissions fb.api");
                console.log(response);
                var permissions = FB_config.PERMISSIONS.split(",");
                for(var i = 0; i < permissions.length; i++)
                {
                    if(response.data[0][permissions[i]] == undefined || response.data[0][permissions[i]] != 1)
                    {
                        jQuery("#FBreauth").show();
                        break;
                    }
                }
            });
        }
        function FBdisplayMyPages(authResponse){
            console.log("FBdisplayMyPages");
            console.log(authResponse);
            FB.api('/me/accounts', function(response) {
                console.log("in FBdisplayMyPages fb.api");
                console.log(response);
                var str = "";
                var name = "";
                var count = 0;
                str += '<optgroup label="Pages">';
                for(var i = 0; i < response.data.length; i++)
                {
                    if(response.data[i].category != "Application")
                    {
                        name = response.data[i].name;
                        str += '<option value="'+response.data[i].id+"_"+response.data[i].access_token+'">'+name+'</option>';
                        count++;
                    }
                }
                str += "</optgroup>";

                jQuery("#msgPostOn").html(str);
                FB.api('/me/groups', function(response) {
                    console.log("in FBdisplayMyPages fb.api 2");
                    console.log(response);

                    str = jQuery("#msgPostOn").html();
                    str += '<optgroup label="Groups">';
                    name = "";

                    for(var i = 0; i < response.data.length; i++)
                    {
                        if(response.data[i].category != "Application")
                        {
                            name = response.data[i].name;
                            str += '<option value="'+response.data[i].id+"_"+authResponse.accessToken+'">'+name+'</option>';
                            count++;

                        }
                    }
                    str += "</optgroup>";
                    jQuery("#msgPostOn").html(str);

                    switch(count)
                    {
                        case 0:
                            // notify that there are not pages. will post to personal page
                            str += '<option value="' + authResponse.userID + "_" + authResponse.accessToken + '">Personal Account</option>';
                            jQuery("#msgPostOn").html(str);
                            jQuery("#FBpostTo").text("No pages found. Posting to your personal account");
                            jQuery("#FBpostTo").show();

                            break;
                        case 1:
                            // only 1 page. hide it...
                            // notify name of page to update

                            jQuery("#msgPostOn").hide();
                            jQuery("#FBpostTo").html("Posting to <strong>" + name + "</strong>");
                            jQuery("#FBpostTo").show();
                            break;
                        default:
                            // notify user to select a page to post to
                            jQuery("#FBpostTo").text("There are multiple groups/pages associated with your account. Specify which to post to ");
                            jQuery("#FBpostTo").show();
                            jQuery("#msgPostOn").show();
                    }
                });
            });
        }
        function FBrefresh(){
            console.log("FBrefresh");
            FB.getLoginStatus(FBverifyLogin);
        }
        function FBreauth(){
            console.log("FBreauth");
            FB.ui(
                {
                    method: 'oauth',
                    display: 'popup',

                    app_id: FB_config.API_ID,
                    client_id: FB_config.API_ID,
                    redirect_uri: "http://www.facebook.com/connect/login_success.html",

                    scope: FB_config.PERMISSIONS
                }
            );          
        }

        function ShowPostToFacebookCheckbox() 
        { 
            console.log("ShowPostToFacebookCheckbox");
            jQuery('#postToFacebook2').css('display', 'inline'); 
            jQuery('#LabelForFacebook').css('display', 'inline'); 
        }

    </script>       

    <div id="fb-root"></div>
<div id="postToFacebookField" class="fieldContainer checkbox ">
    <div id="btnLogin" class="fb-login-button" scope="publish_stream,manage_pages,user_groups">Login with Facebook</div>
    <input type="checkbox" style="display:none" name="postToFacebook2" value="on" id="postToFacebook2"> 
    <label style="cursor: pointer; display:none" for="postToFacebook2" id="LabelForFacebook">Post to Facebook Page</label>
    <div id="FBpostTo" style="display: none"></div>
    <select id="msgPostOn" style="display: none"></select>
    <div style="display: none" id="FBreauth">(Insufficient permissions. <a href ='#' onclick='FBreauth(); return false;'>Authorize this app</a> and <a href='#' onclick='FBrefresh() ; return false'>refreshing</a>)</div>
</div>

3 个答案:

答案 0 :(得分:2)

如果您仍在寻找这个问题的解决方案,我相信我有一些可能在您设置的约束条件下工作的东西。很简单,我们只清除内存中的所有加载变量和对象,以及我的测试,包括facebook附加的<script>

将test.htm中的click处理程序替换为this,它应该可以正常工作

jQuery(document).ready(function(){
    jQuery("#lnk").click(function(e){
        if(FB && document.getElementById("facebook-jssdk")){ //if set, reset
              //removes the <script>
          document.head.removeChild(document.getElementById("facebook-jssdk")); 
          window.FB=null; //unloads the APIs
          loaded=null; 
        }
        e.preventDefault();
        jQuery("#divContent").load("test.htm", function(){
            if(loaded)
            {
                FB.getLoginStatus(FBverifyLogin);
            }
            else
            {   
                loaded = true;
            }
        });
    });
});

答案 1 :(得分:1)

我们遇到了类似的问题,这篇文章http://www.martincarlin.info/facebook-js-sdk-not-working-on-second-load-of-ajax-loaded-page/帮助我们解决了这个问题。

脚本无法运行的原因是因为window.fbAsyncInit函数在初始页面加载时运行,所以第二次进行AJAX调用时,Facebook JavaScript SDK已经加载到页面中,因此window.fbAsyncInit不会再次开火。

通过检查FB是否已经定义,我们可以在没有初始化部分的情况下使用我们的SDK代码。

希望能帮助您解决问题。

答案 2 :(得分:1)

在尝试了过去几天的所有内容后,下面这段代码对我有用。

//intialize FB object (this is useful if you are using Turbolinks)
$(document).on('page:load', function(){
 intializeFB();
});

intializeFB();

function intializeFB(){
 if(typeof(FB) !== "undefined"){
  delete FB;
 }
 $.getScript("http://connect.facebook.net/en_US/all.js#xfbml=1",      function () {
   FB.init({
     appId      : '19871816653254',
     cookie     : true,  // enable cookies to allow the server to access 
                         // the session
     xfbml      : true,  // parse social plugins on this page
     oauth      : true,
     status     : true,
     version    : 'v2.4' // use version 2.4
   });
 });
}

希望这很有用!