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

时间:2013-07-11 14:19:00

标签: php jquery settimeout

我遇到的问题是,在实际分配值之前尝试附加到页面的ajax调用获取的值。例如,当调用下面的sendRequest时,我每次都会从网络获得价格响应,但是当我在console.log中时,我有时会得到未定义的。请参阅粗体注释。我已经尝试使ajax请求同步和一个真正的贫民区setTimeout函数,但我仍然得到occassional undefined。如何确保价格附加到页面?如果我今天很慢,请对我好: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调用返回正确的值):

Console Network

2 个答案:

答案 0 :(得分:1)

正如你所说,它在90%的时间里工作正常,所以我假设90%的时间没有执行这个if块,而是在其他10%的时间内执行它

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

如果执行此块,并且尝试使用此行记录

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

此时discountPercentundefined,因为您没有在第一个if块中计算

答案 1 :(得分:0)

我想,for会向您的服务器生成太多请求。因此,服务器响应可能不是200.您应该查找jQuery.ajax的属性error,然后在尝试将setTimeout(...) ...移至error部分时捕获响应。