dqhbuwrwq692118284 2013-07-11 14:18
浏览 48
已采纳

异步javascript问题,即使网络有响应,也会将未定义的内容附加到页面

I am having an issue with the values obtained from an ajax call attempting to append to the page before the value is actually assigned. For example, when sendRequest below is called I am getting a price response from the network each time, but when I console.log it, sometimes I get undefined. See comments in bold. I have tried making ajax request synchronous and a really ghetto setTimeout function, but I still get the occassional undefined. How can I make sure the price gets appended to the page? Please be nice to me if I'm being slow today :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);
}   

Update Prices ajax call 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); 
?>

Response screen shot (all ajax calls are returning correct values):

ConsoleNetwork

  • 写回答

2条回答 默认 最新

  • ds08541 2013-07-11 15:27
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog