简体   繁体   English

登录后如何将Facebook用户ID转到另一个JavaScript文件?

[英]How to get the facebook user id to another javascript file after login?

I understand that I can get the facebook id by doing: 我了解可以通过以下方式获取Facebook ID:

FB.api('/me', function(response) {
  alert('Your id is ' + response.id);
});

However, I want to have the user login and then grab that id in a different file so I can handle it. 但是,我想让用户登录,然后在另一个文件中获取该ID,以便我进行处理。 Right now I have: 现在我有:

var id = "";
var fburl = "http://graph.facebook.com/" + id + "?callback=?"

$(function(){
    $("#fb-profile-picture")[0].src = "http://graph.facebook.com/" + id +"/picture";

    $.getJSON(fburl, function(data){
        console.log(data);
        $("#name").append(data.name);
        $("#user-id").append(data.id);
    });

});

and if I manually enter the id in the id var it works however I'd like to be able to grab that response.id as the value and use it in this other javascript file but I haven't figured out how to. 并且,如果我在id var中手动输入id ,它可以工作,但是我希望能够将那个response.id作为值,并在其他JavaScript文件中使用它,但我还没有弄清楚该怎么做。

Assuming you 假设你

  • cannot control which of the scripts is executed first 无法控制首先执行哪个脚本
  • you are working in an environment with a global window object 您正在使用具有全局窗口对象的环境
  • part one is only executed once 第一部分仅执行一次
  • you are using jQuery 您正在使用jQuery

making a global and firing an event might be a solution, although not considered best practice. 尽管不认为最佳做法,但进行全局和触发事件可能是解决方案。

Script 1: 脚本1:

FB.api('/me', function(response) {
  window.fbCustomId = response.id;
  console.log(window.fbCustomId);
  $(window).trigger('fbResponseLoaded');
});

Script 2: 脚本2:

function renderProfile() {
    var fburl = "//graph.facebook.com/" + window.fbCustomId + "?callback=?"

    $(function () {
        $("#fb-profile-picture")[0].src = "//graph.facebook.com/" + window.fbCustomId + "/picture";

        $.getJSON(fburl, function (data) {
            console.log(data, window.fbCustomId);
            $("#name").append( $('<span>').text(data.name) );
            $("#user-id").append( $('<span>').text(data.id) );
        });

    });
}
if (window.fbCustomId) {
    renderProfile();
} else {
    $(window).on('fbResponseLoaded', renderProfile);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM