如何获得str变量的值? [英] How to get the value of str variable?

查看:56
本文介绍了如何获得str变量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用FB API获取URL(str变量).

I'm trying to get the URL (str variable) using FB API.

当我尝试 CONSOLE2 console.log(str)时,它显示了包含照片URL的 str 变量的确切值.

When I tried CONSOLE2 console.log(str) it showed the exact value of str variable which contains URL for photo.

但是当我尝试 CONSOLE1 时,它不起作用.它什么也没打印.

But when I tried CONSOLE1 it didn't work. It printed nothing.

是因为某些异步功能吗?如果是,如何编写以下两个语句(请参见注释1 )后起作用的代码(一个接一个地执行不重要,我只想在 CONSOLE1 中使用该URL)我叫getPhoto())

Is it because of some async functions? If yes, how can write the code that following two statements (see Note 1) work (it doesn't matter one executes after another, I just want the URL in CONSOLE1 where I have called getPhoto())

注1:这两个语句均表示location.href和CONSOLE1,以确保我在Login()函数中获取了 str 的值.

Note 1: Both statements mean the location.href and CONSOLE1, to ensure that I'm getting the value of str inside the Login() function.

  function Login()
  {         
    FB.login(function(response) {
       if (response.authResponse) 
       {
          getPhoto();
         // window.location.href="quiz.html";
          //**CONSOLE1** 
          console.log(str);
         } else 
        {
           console.log('User cancelled login or did not fully authorize.');
        }
     },{scope: 'email,user_photos,user_videos,publish_actions'});
  }

  function getPhoto()
  {
    FB.api('/me/picture?type=normal', function(response) {
      var str="<br/><b>Pic</b> : <img src='"+response.data.url+"'/>";
        document.getElementById("status").innerHTML+=str;
         //**CONSOLE2**
         console.log(str);     
    });
  }

推荐答案

这是怎么回事:

function Login() {       
    FB.login((response) => {
        if (response.authResponse) {
            getPhoto((str) => {
                console.log(str);
            });
        } else {
            console.log('User cancelled login or did not fully authorize.');
        }
    },{scope: 'email,user_photos,user_videos,publish_actions'});
}

function getPhoto(callback) {
    FB.api('/me/picture?type=normal', (response) => {
        const str = '<br/><b>Pic</b> : <img src="' + response.data.url + '"/>';
        document.getElementById('status').innerHTML += str;
        callback(str);     
    });
}

也有其他解决方案(例如,使用Promises),但是使用回调函数非常容易.我还添加了ES6语法(常量,箭头功能).

There are other solutions too (for example, with Promises), but using a callback function is very easy. I also added ES6 syntax (const, arrow functions).

您还可以使用FB.getLoginStatus检查用户是否在页面加载时登录,并在该函数的回调中也调用getPhoto.

You can also use FB.getLoginStatus to check if the user is logged in on page load, and call getPhoto in the callback of that function too.

例如: http://www.devils-heaven.com /facebook-javascript-sdk-login/

这篇关于如何获得str变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆