我用来登录用户的 Facebook Graph API 代码调用了我的getfriends()
循环函数两次。如何更改代码以使循环函数仅调用一次,同时仍允许处于各种状态的用户登录?
<html xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<title>FB App</title>
<script>
var userList = [];
userCount = 0;
function getfriends () {
console.log("getFriends");
var url = "/me/friends";
FB.api(url, function (response) {
userList = userList.concat(response.data);
userCount = response.data.length;
compareAllFriends();
});
}
function compareAllFriends () {
console.log("compareAllFriends");
var i = 0, l = 10, userID;
for (; i < l; i += 1) {
userID = userList[i].id;
compareFriendsWith (i, userID);
}
}
function compareFriendsWith (i, id) {
console.log("compareFriendsWith", i, id);
}
</script>
</head>
<body>
<div id="fb-root"></div>
<p align="right"><button id="fb-auth">Login</button></p>
<script type="text/javascript">// <![CDATA[
window.fbAsyncInit = function() {
FB.init({ appId: 'APP_ID',
status: true,
cookie: true,
xfbml: true,
oauth: true});
function updateButton(response) {
var button = document.getElementById('fb-auth');
if (response.authResponse) {
//user is already logged in and connected
FB.api('/me', function(response) {
getfriends();
button.innerHTML = 'Logout';
});
button.onclick = function() {
FB.logout();
};
} else {
//user is not connected to your app or logged out
button.innerHTML = 'Login with Facebook';
button.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me');
} else {
//user cancelled login or did not grant authorization
}
}, {scope:''});
}
}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
// ]]></script>
</body>
</html>