Saturday, November 17, 2012

javascript – Jquery/JS scoping

This may be pretty simple but it\’s stumping me. I\’m trying to return a variable in javascript to another variable outside of the function\’s scope. For some reason, the assignment isn\’t occurring. Here\’s my code:



var time = Math.round(((new Date()).getTime())/1000);

// first call to get data
var power_now = get_data(<%= @user.id %>, time);

function get_data(user_id, timestamp){
var targetURL = \"get/user_data?time_now=\"+timestamp+\"&user_id=\"+user_id;
var power = 0;

$.get(targetURL, function(data){
power = data[0][\'power\'];
alert(power);
})

return power;
}

$(\'body\').html(\'<h1>\'+power_now+\',\'+power_then+\'</h1>\')


If I place alert(power) within the .get function, the value is correct; however if I place it outside of the .get function, the value is 0.


Maybe I\’m missing something about scoping in javascript?


Thanks!






Rating: 2 out of 5 based on 3 ratings



The post javascript – Jquery/JS scoping appeared first on Javascript ASK.






via Javascript ASK http://javascriptask.phpfogapp.com/javascript-jqueryjs-scoping.html

No comments:

Post a Comment