在jquery ajax完成函数问题中为数组赋值

时间:2013-09-10 22:34:18

标签: php javascript jquery magento

我正在尝试将数据库中位置的距离添加到名为distance的数组中。似乎我的数组在完成它的循环之前被清空和/或循环的索引没有在每个循环完成之前重新分配'x'的值。你能看出我做错了什么吗?我是否需要某处的回调功能?

<?php if (isset($customer_id)) {?>
                        customer_id = <?=$customer_id?>;
                    <?php }?>

                    //var distances = new Array();

                        $j.ajax({
                            type: "POST",
                            url: "/ajax_calls/originDestinationAddress.php",
                            data: { 'vendorID': <?=$vendorId?>, 'customerID': customer_id}
                            }).done(function(data) {
                                var data= JSON.parse(data);     
                                var destination = data[0].destination;
                                console.log ('destination is ' + destination);

                                var distances = [];
                                for(var x=0; x<data.length; x++){
                                console.log('the array of distances for vendor with id ' + <?=$vendorId?>);
                                    var origin = data[x].origination;
                                    console.log('origin is ' + origin);

                                    if(origin && destination){
                                        var service = new google.maps.DistanceMatrixService();
                                          service.getDistanceMatrix(
                                            {
                                              origins: [origin],
                                              destinations: [destination],
                                              travelMode: google.maps.TravelMode.DRIVING,
                                              unitSystem: google.maps.UnitSystem.IMPERIAL,
                                              avoidHighways: false,
                                              avoidTolls: false
                                            }, function(response, status){
                                                if (status != google.maps.DistanceMatrixStatus.OK) {
                                                    console.log('Error was: ' + status);
                                                  } else {
                                                    var origins = response.originAddresses;
                                                    var destinations = response.destinationAddresses;

                                                    for (var i = 0; i < origins.length; i++) {
                                                      var results = response.rows[i].elements;
                                                      for (var j = 0; j < results.length; j++) {
                                                        var miles = results[j].distance.text;
                                                        var pieces = miles.split(" ");

                                                            //$j('#'+ id + ' td.distanceDetail').text(pieces[0]);
                                                            //$j('#'+ id + ' td.distanceDetail').append('<span> ' + pieces[1] + '</span>');
                                                            console.log('currently adding ' + pieces[0] + ' to distances array with key ' + x);
                                                            distances[x]= pieces[0];
                                                      }
                                                    }
                                                  }
                                            });
                                }//end for length of data loop
                                console.log(distances);
                            }


                        });//end done function

originDestinationAddress.php(接收Chrome开发人员检查的所有正确的标题,因此不应该相关):

<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
require_once('/connect.php');
require_once('/app/Mage.php');
umask(0);
Mage::app(); 


$vendorID = $_POST['vendorID'];
//$vendorID=13;
$customerID = $_POST['customerID'];
//$customerID=8;


//Must convert ID to match Zak's program
    $productModel = Mage::getModel('catalog/product');
    $attr = $productModel->getResource()->getAttribute("vendor");
    if ($attr->usesSource()) {
        $vendorID= $attr->getSource()->getOptionText($vendorID);
    }   



$customerData = Mage::getModel('customer/customer')->load($customerID);
$customerSchool = addslashes($customerData->getSchool());
$pieces = explode("-", $customerSchool);


//obtain origination
        $sql = mysqli_query($con,'SELECT street_1, street_2, city, state, zipcode, zip4 FROM DTS_Mage_Staging.ven_ship_orig WHERE ven_id=' . $vendorID);
        $i=0;
        //echo 'SELECT street_1, street_2, city, state, zipcode, zip4 FROM DTS_Mage_Staging.ven_ship_orig WHERE ven_id=' . $vendorID;
        while($row = mysqli_fetch_array($sql)){
            $addressString= $row['street_1'] . ', ';
            if($row['street_2']!="" && $row['street_2']!="null")
                $addressString.= $row['street_2'] . ", ";
            $addressString.= $row['city'] . ", " . $row['state'] . " " . $row['zipcode'];
            if($row['zip4']!="" && $row['zip4']!="null")
                $addressString.= "-" . $row['zip4'];
            $addressString.= ", USA";
            $echoArray[$i]['origination'] = $addressString;
            $i++;
        }


        //while($row = mysqli_fetch_array($sql)){
            //$echoArray[$i]['origination']= $row['ship_city'] . "," . $row['ship_state'];
            //$i++;
        //}

//obtain destination    
if ($pieces[0] == "District Purchaser"){
    $sql2 = mysqli_query($con,"SELECT mail_city,mail_state FROM dist_comp.districts WHERE agency_name='" . $pieces[1] . "'");
        $i=0;
        while($row = mysqli_fetch_array($sql2)){
            $echoArray[$i]['destination']= $row['mail_city']. "," . $row['mail_state'];
            $i++;
        }
}else{  
    $sql2 = mysqli_query($con,"SELECT ship_city,ship_state FROM dist_comp.schools WHERE school_name='" . $customerSchool . "'");
        $i=0;
        while($row = mysqli_fetch_array($sql2)){
            $echoArray[$i]['destination']= $row['ship_city']. "," . $row['ship_state'];
            $i++;
        }

            $sql3 = mysqli_query($con,"SELECT city,state FROM dist_comp.private_schools WHERE school_name='" . $customerSchool . "'");
            $i=0;
            while($row = mysqli_fetch_array($sql3)){
                $echoArray[$i]['destination']= $row['city'] . "," . $row['state'];
                $i++;
            }
        //} 
}
echo json_encode($echoArray); 

?>

控制台截图 enter image description here

1 个答案:

答案 0 :(得分:0)

哇,这很难读!

它看起来像你标记为的大括号:

//end for length of data loop

实际上是关闭支柱:

if(origin && destination){

大括号直接位于:

之后
console.log(distances);

是data.length循环的结束括号。

我认为您要做的是移动console.log(distances)

到你的.done()回调结束之前的那一行:

        }//end for length of data loop

    }
    console.log(distances);

});//end done function