I'm trying to a code a script that 1) Reads FB user IDs from text input fields & loops them into an array 2) calls FB.api with each of the IDs for first name and saves the returned first name value into another array. The problem: for some reason, all the first names received from FB.api save to the same array index place 5. Which is extra weird since the loop should only go from indexes 1 to 4.
<script type="text/javascript">
var ids = new Array();
var names = new Array();
var fields = 4;
function firstNames() {
var i;
var k;
for (i=1;i<=fields;i++)
{
ids[i] = document.开发者_StackOverflow社区getElementById("field"+i).value;
}
for (k=1; k<=fields; k++)
{
FB.api('/'+ids[k], function(response) {
names[k] = response.first_name;
alert(k+' test '+names[k]);
});
}
}
</script>
Has anyone ran into something similar? Any help would be much appreciated.
Thanks beforehand.
Read: Javascript, node.js and for loops
See: Experiment #7: Closure with new scope establishing a new variable
URL: http://blog.mixu.net/2011/02/03/javascript-node-js-and-for-loops
I had the same issue as you i.e. FB.api gets the FOR loops final iteration index...
Please try this solution:
for (k=1; k<=fields; k++)
{
// Closure with new scope establishing a new variable
(function() {
var index = k; // new variable
FB.api('/'+ids[index], function(response) {
names[index] = response.first_name;
alert(index+' test '+names[index]);
});
}();
}
Update: One thing to note is that the alerts in this example probably won't happen in sequence i.e. you might get 1,4,2,3... it all depends on network latency of each API call as to the order they are executed in ...
It wasn't the same Api call but i actually ran into something similar.
You have to understand that the facebook api call is asynchronous. And most importantly, it's slow. So javascript is way faster, and by the time the first response is sent, your javascript for loop is already completed. That's why everything is sent into k=5, which is k's value after the loop.
This is happening because javascript doesn't force you to use a final variable in the handler, like java does.
So now you understand, how to fix it ? Heh sorry, i came out with a dirty solution when i had this kind of problem.
What I did was handling the code directly in the function(response) body, and not use intermediary variables. So as a quick fix you can do the same and forget about your names array, or find something better.
精彩评论