0

我对从试图在实际分配值之前附加到页面的 ajax 调用获得的值有疑问。例如,当调用下面的 sendRequest 时,我每次都会从网络获得价格响应,但是当我 console.log 时,有时我会得到未定义。见粗体评论。我曾尝试使 ajax 请求同步和一个真正的贫民窟 setTimeout 函数,但我仍然得到偶尔的未定义。如何确保将价格附加到页面?如果我今天很慢,请对我好 :D

function updatePrices(IDs,callback){
    var product_id= <?=$product_id ?>;
    var qty= parseInt($j("#qtyUpdateBox input").val());
    var customer_id = null;

    <?php if (isset($customer_id)) {?>
        customer_id = <?=$customer_id?>;
        //$j('#vendorPriceListHeading').css({
            //'width': '230px',
            //'margin-left':'105px',
            //'margin-right':'-80px'
        //  });
    <?php }?>

    if (qty==1){
        function sendRequestOne(i) {
            var optionSelectionArray = currentlySelectedAttributes(IDs[i]);

            simpleWithAttrPrice(optionSelectionArray, customer_id, qty, function(data) {
                var data= JSON.parse(data);
                var unitPrice = parseFloat(roundDollar(data.basePrice));

                $j('.details'+IDs[i]+ ' .priceBlock').empty();      
                $j('.details'+IDs[i]+ ' .priceBlock').append('<span>'+formatCurrency(unitPrice,"$")+'</span>');

                $j('.details'+IDs[i]+ ' .vendorCheck input[name="customPrice"]:checked').val(unitPrice);
            });
        }//end sendRequest

        for(i=0; i<IDs.length; i++)
        {   
            sendRequestOne(i);
        }

    }//end if
    else{
        //ajax call to obtain tier prices for each vendor id
        function sendRequest(i,qty,product_id){
            var vendor = IDs[i]; 
            $j.ajax({
                    type: "POST",
                    url: "/ajax_calls/updatePrices.php",
                    async:false,
                    data: { 'vendorID': vendor, 'product_id': product_id}
                    }).done(function(data) {
                        //CAITLIN below may need to be parsed in the php script
                            var data= JSON.parse(data);

                            var optionSelectionArray = currentlySelectedAttributes(vendor);

                            simpleWithAttrPrice(optionSelectionArray, customer_id, qty, function(price) {
                                var price= JSON.parse(price);
                                var unitPrice = roundDollar(parseFloat(price.basePrice));
                                var pricexQty= unitPrice * qty;


                                if (qty < data.tier2_range_start){
                                    var unitPrice = totalPrice/qty;
                                }
                                else if (qty >= data.tier2_range_start && qty < data.tier3_range_start){
                                    var discountPercent = data.tier2_discount;
                                    var discount = pricexQty * data.tier2_discount / 100;
                                    var totalPrice = pricexQty - discount;
                                }
                                else if (qty >= data.tier3_range_start && qty < data.tier4_range_start){
                                    var discountPercent = data.tier3_discount;
                                    var discount = pricexQty * data.tier3_discount / 100;
                                    var totalPrice = pricexQty - discount;
                                }
                                else if (qty >= data.tier4_range_start && qty < data.tier5_range_start){
                                    var discountPercent = data.tier4_discount;
                                    var discount = pricexQty * data.tier4_discount / 100;
                                    var totalPrice = pricexQty - discount;
                                }
                                else if (qty >= data.tier5_range_start){
                                    var discountPercent = data.tier5_discount;
                                    var discount = pricexQty * data.tier5_discount / 100;
                                    var totalPrice = pricexQty - discount;
                                }
                                else{
                                    console.log('Something went wrong');
                                }
                                var unitPrice = roundDollar(totalPrice/qty); //unitPrice including Shipping

                                setTimeout(function(){
                                    //BELOW IS LOGGING UNDEFINED SOMETIMES, BUT AJAX RESPONSE HAS THE VALUES
                                    console.log("The unit price is " + unitPrice + " and the discount percent is " + discountPercent);

                                    $j('.details'+vendor+ ' .priceBlock').empty();//update product price in DOM
                                    $j('.details'+vendor+ ' .priceBlock').append('<span>'+formatCurrency(unitPrice,"$")+'</span>');
                                    //$j('.details'+data.vendor_id+ ' .priceBlock').append('<span>Total Price: '+formatCurrency(unitPrice*qty,"$")+'</span>');
                                    $j('.details'+vendor+ ' .vendorCheck input[name="customPrice"]:checked').val(unitPrice);
                                    $j('.details'+vendor+ ' .priceBlock').append('<h5 style="color:green">You will save '+discountPercent+'% !</h5>');
                                },1000);
                        });//end callback function

                        //reorderByPrice();

                    });//end done function
                }//end function sendRequest

        for(i=0; i<IDs.length; i++)
        {   
            sendRequest(i,qty,product_id);
        }
    }//end else


    if (callback) {
        setTimeout(callback, 1);
    }
}//end function 



function simpleWithAttrPrice(optionSelectionArray, customer_id, qty, callback){
    var product_id= <?=$product_id ?>;

        $j.ajax({
            type: "POST",
            url: "/ajax_calls/obtainBasePrice.php",
            data: { 'productID': product_id, 'optionSelectionArray' : optionSelectionArray, 'customer_id': customer_id, 'qty': qty} 
            }).done(callback);
}   

更新价格 ajax 调用 PHP:

<?php
$dbname='secret';
require_once('/connect.php');
require_once('/app/Mage.php');
umask(0);
Mage::app(); 
$productModel = Mage::getModel('catalog/product');
$attr = $productModel->getResource()->getAttribute("vendor");


//post variable
$ID= $_POST['vendorID'];
//$ID= 1497;
//echo 'the id is initially ' .$ID;

if ($attr->usesSource()) {
    $ID= $attr->getSource()->getOptionText($ID);
    //echo $ID;
}
$product_id= $_POST['product_id'];
$echoArray= array();

if($ID == 3|| $ID ==4 || $ID ==11 || $ID ==12 || $ID ==13)
    $sql = 'SELECT * FROM tier_pricing WHERE vendor_id=' . $ID;
else
    $sql = 'SELECT * FROM tier_pricing WHERE vendor_id=' . $ID. ' AND product_id=' . $product_id;
    foreach ($con->query($sql) as $row) {
        $echoArray['vendor_id']= $row['vendor_id'];
            $echoArray['tier2_range_start']= $row['tier2_range_start'];
        $echoArray['tier2_range_stop']= $row['tier2_range_stop'];
        $echoArray['tier3_range_start']= $row['tier3_range_start'];
        $echoArray['tier3_range_stop']= $row['tier3_range_stop'];
        $echoArray['tier4_range_start']= $row['tier4_range_start'];
        $echoArray['tier4_range_stop']= $row['tier4_range_stop'];
        $echoArray['tier5_range_start']= $row['tier5_range_start'];
        $echoArray['tier2_discount']= $row['tier2_discount'];
        $echoArray['tier3_discount']= $row['tier3_discount'];
        $echoArray['tier4_discount']= $row['tier4_discount'];
        $echoArray['tier5_discount']= $row['tier5_discount'];
    }

echo json_encode($echoArray); 
?>

响应屏幕截图(所有 ajax 调用都返回正确的值):

安慰 网络

4

2 回答 2

1

As you are saying it works fine 90% of the time so i assume 90% of the time this if block is not get executed and its get executed other 10% of the time

if (qty < data.tier2_range_start){
   var unitPrice = totalPrice/qty;
}

If this block gets executed and than if you try to log using this line

console.log("The unit price is " + unitPrice + " and the discount percent is " + discountPercent);

At this point discountPercent is undefined because you are not calculating it in the first if block

于 2013-07-11T15:27:08.910 回答
0

我想,这for对您的服务器产生了太多的请求。因此,服务器响应可能不是 200。您应该查找jQuery.ajaxerror的属性并在您尝试移动到该部分后捕获响应。setTimeout(...) ...error

于 2013-07-11T14:30:50.217 回答