Get var out of jQuery.get nested function
function getUserHours(tyPe, tarGet){
$.get('/activities/search', { 'type': tyPe },
function(data){
var hourResultData = jQuery.parseJSON(data);
var registeredHours = 0;
for (var i in hourResultData.activities){
registeredHours += parseFloat(hourResultData.activities[i].hours);
}
$(tarGet).empty().append(registeredHours);
return registeredHours;
});
}
I want:
alert( getUserHours('r', '#reg-hours'));
to alert re开发者_Python百科gisteredHours
Returning data directly will only work if you turn the asynchronous GET for AJAX off:
$.ajax({
type: 'GET',
url: '/activities/search',
data: { 'type': tyPe },
async : false,
success : function() { }
});
This is not recommended, because the browser will block until you request is finished. Instead you should continue to follow the asynchronous programming model by using function callback:
$.ajax({
type: 'GET',
url: '/activities/search',
data: { 'type': tyPe },
async : false,
success : function() { }
});
function getUserHours(tyPe, tarGet, callback)
{
$.get('/activities/search', { 'type': tyPe },
function(data)
{
var hourResultData = jQuery.parseJSON(data);
var registeredHours = 0;
for (var i in hourResultData.activities){
registeredHours += parseFloat(hourResultData.activities[i].hours);
}
$(tarGet).empty().append(registeredHours);
if($.isFunction(callback))
callback(registeredHours);
});
}
getUserHours('r', '#reg-hours', function(hours) {
alert(hours);
});
The callback function you're trying to return from is called when the data is ready, meaning the data is sent asyncronously.
This means you can't return the data directly from your getUserHours
function. You need a callback function to fire when the data is ready.
Something like this:
function getUserHours(tyPe, tarGet, callback){
$.get('/activities/search', { 'type': tyPe },
function(data){
var hourResultData = jQuery.parseJSON(data);
var registeredHours = 0;
for (var i in hourResultData.activities){
registeredHours += parseFloat(hourResultData.activities[i].hours);
}
$(tarGet).empty().append(registeredHours);
callback(registeredHours); // callback, send back data to callback function
});
}
Then send an anonymous function as a parameter in getUserHours
.
getUserHours('r', '#reg-hours', function(data) {
alert(data);
});
精彩评论