Get var out of jQuery.get nested function

前端 未结 2 543
醉酒成梦
醉酒成梦 2021-01-26 09:56
  function getUserHours(tyPe, tarGet){
    $.get(\'/activities/search\', { \'type\': tyPe }, 
    function(data){   
     var hourResultData = jQuery.parseJSON(data);
           


        
2条回答
  •  无人共我
    2021-01-26 10:23

    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);
    });
    

提交回复
热议问题