【问题标题】:Return value from function and place into variable in separate function从函数返回值并放入单独函数中的变量
【发布时间】:2013-12-22 10:12:16
【问题描述】:

我试图从一个单独的函数中获取 var newtotal 的值,然后通过 Ajax 将该值传递给 PHP 脚本。

这是我的代码:`

function customerCost(){

        var newtotal;

        var start = document.getElementById('source').value;
        var end = document.getElementById('destination').value;
        var via = document.getElementById('via').value;

        if(via != ""){
        var waypts = [];

        waypts.push({
            location:via,
            stopover:false});

        var newrequest = {
          origin: start,
          destination: end,
          waypoints: waypts,
          travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(newrequest, function(newresponse, newstatus) {
          if (newstatus == google.maps.DirectionsStatus.OK) {

            var newtotal = 0;
            var mynewroute = newresponse.routes[0];
             for (i = 0; i < mynewroute.legs.length; i++) {
                 newtotal += mynewroute.legs[i].distance.value;
                }
                            return newtotal;
            }

        });

        }else{

            var newrequest = {
          origin: start,
          destination: end,
          travelMode: google.maps.DirectionsTravelMode.DRIVING
        };
        directionsService.route(newrequest, function(newresponse, newstatus) {
          if (newstatus == google.maps.DirectionsStatus.OK) {

            var newtotal = 0;
            var mynewroute = newresponse.routes[0];
             for (i = 0; i < mynewroute.legs.length; i++) {
                 newtotal += mynewroute.legs[i].distance.value;
                }
                return newtotal;
            }

        });

        }



    }

然后我从一个单独的函数中调用该值,如下所示:

customertotal = customerCost();

我只收到“未定义”错误。但是,如果我将return newtotal; 替换为alert(newtotal);,那么它会输出正确的值。

我哪里出错了?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    directionsService.route() 调用是异步的。这意味着当您调用它时,它只会启动操作,而您的 customerCost() 函数会继续并在 .route() ajax 调用完成并调用其回调之前很久就完成。

    您正在尝试使用异步操作以同步方式进行编程。你不能那样做。您的 customerCost() 函数调用无法返回 newtotal 值,因为在该函数返回时它还不知道。

    相反,您需要学习如何以异步方式编程。任何需要newtotal 值的代码都需要在该值可用的回调中,或者您可以从那里调用一个函数并将newtotal 值传递给它。

    开发这样的东西的典型方法可能是使用您自己的回调:

    function customerCost(cb){
    
            var newtotal;
    
            var start = document.getElementById('source').value;
            var end = document.getElementById('destination').value;
            var via = document.getElementById('via').value;
    
            if(via != ""){
            var waypts = [];
    
            waypts.push({
                location:via,
                stopover:false});
    
            var newrequest = {
              origin: start,
              destination: end,
              waypoints: waypts,
              travelMode: google.maps.DirectionsTravelMode.DRIVING
            };
            directionsService.route(newrequest, function(newresponse, newstatus) {
              if (newstatus == google.maps.DirectionsStatus.OK) {
    
                var newtotal = 0;
                var mynewroute = newresponse.routes[0];
                 for (i = 0; i < mynewroute.legs.length; i++) {
                     newtotal += mynewroute.legs[i].distance.value;
                  }
                  // call the callback and pass it the newtotal
                  cb(newtotal);
                }
    
            });
    
            }else{
    
                var newrequest = {
              origin: start,
              destination: end,
              travelMode: google.maps.DirectionsTravelMode.DRIVING
            };
            directionsService.route(newrequest, function(newresponse, newstatus) {
              if (newstatus == google.maps.DirectionsStatus.OK) {
    
                var newtotal = 0;
                var mynewroute = newresponse.routes[0];
                 for (i = 0; i < mynewroute.legs.length; i++) {
                     newtotal += mynewroute.legs[i].distance.value;
                    }
                    // call the callback and pass it the newtotal
                    cb(newtotal);
                }
    
            });
    
        }
    }
    
    
    // call the asynchronous cost function and process the result
    // in a callback function
    customerCost(function(newtotal) {
        // the newtotal value is available here
    });
    

    【讨论】:

    • 太棒了。我今天学到了一些新东西。非常感谢您的耐心和帮助。
    【解决方案2】:

    你应该使用回调函数来处理异步函数中的变量。

    您可以添加回调函数作为参数:

    customerCost(callback){
    
      // your original code
    }
    

    然后将return newtotal之类的所有行替换为callback(newtotal);

    然后调用函数customerCostlike:

    customerCost(function(customertotal){
      // work with customertotal
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-23
      相关资源
      最近更新 更多