从JavaScript回调函数检索值 [英] Retrieving value from javascript callback function
问题描述
var display_welcome = function(){
var fb_login_button = jQuery('#fb_login_button');
var fb_welcome = jQuery('#fb_welcome');
var name = '';
FB.api('/me',function(response){
console.log(response);
name = response.first_name;
});
fb_login_button.css('display', 'none');
fb_welcome.html('<span>Welcome, ' + name + '</span>');
fb_welcome.css('display', 'block');
};
当用户从网站登录Facebook时调用此函数。目标是以用户的名字向用户显示欢迎消息。问题是变量'name'是FB.api()的回调方法范围内的局部变量。
This function is called when a user logs into Facebook from a website. The goal is to display a welcome message to the user with the user's first name. The problem is the variable 'name' is a local variable inside the scope of the callback method of FB.api(). What is the best way to extract this value and use it in my function 'display_welcome'?
推荐答案
如何移动这些行代码到API的回调中?像这样:
How about moving those lines of code into the callback of the API? Like so:
var display_welcome = function(){
var fb_login_button = jQuery('#fb_login_button');
var fb_welcome = jQuery('#fb_welcome');
var name ='';
var display_welcome = function(){ var fb_login_button = jQuery('#fb_login_button'); var fb_welcome = jQuery('#fb_welcome'); var name = '';
FB.api('/me',function(response){
console.log(response);
name = response.first_name;
fb_login_button.hide();
fb_welcome.html('<span>Welcome, ' + name + '</span>');
fb_welcome.show();
});
};
这篇关于从JavaScript回调函数检索值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!