Get var out of jQuery.get nested function

前端 未结 2 537
醉酒成梦
醉酒成梦 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:13

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

提交回复
热议问题