javascript - 从函数返回值并放入单独函数中的变量

标签 javascript

我试图从一个单独的函数获取 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);,那么它会输出正确的值。

我哪里错了?

最佳答案

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

关于javascript - 从函数返回值并放入单独函数中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20728291/

相关文章:

javascript - 用于声明客户端包含的 ASP.NET 指令约定

javascript - 文档.getElementById

javascript - 如何使用 Restangular 仅 PUT 某些字段?

javascript - 当 jquery 显示另一个 div 时,我如何隐藏一个 div?

javascript - Bootstrap Popovers(和一般的 Bootstrap )不工作

javascript - 背景位置图像叠加(适用于 IE,不适用于 Mozilla/Chrome/Safari)

javascript - 如何通过 JSON 更新具有多个系列的 Highcharts?

javascript - 重写一个函数,使其可以在旧版浏览器中运行

javascript - 在设计中 : How can I get paragraph contents with its characterStyles?

javascript - Node.js 返回文件结果