1

我有一个 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>
4

3 回答 3

2

如果您仍在寻找解决此问题的方法,我相信我有一些可能在您设置的限制范围内起作用。很简单,我们只需清除内存中所有加载的变量和对象,以及我的测试,包括<script>facebook 附加的。

用这个替换 test.htm 中的点击处理程序,它应该可以工作

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;
            }
        });
    });
});
于 2014-05-13T13:35:04.463 回答
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 代码。

希望这将帮助您解决问题。

于 2013-10-10T09:34:13.730 回答
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
   });
 });
}

希望这是有用的!

于 2015-09-26T22:01:29.730 回答