2013-07-11 41 views
0

我有一個問題,從實際分配值之前試圖追加到頁面的ajax調用獲得的值。例如,當下面的sendRequest被調用時,我每次都會從網絡獲得價格響應,但是當我console.log時,有時會得到未定義的值。以粗體顯示評論。我已經嘗試使ajax請求同步和一個真正的貧民區setTimeout函數,但我仍然得到未定義的偶爾。我如何確保價格被附加到頁面上?如果我今天正在緩慢請善待我:d異步JavaScript問題,即使網絡有迴應但附加到頁面undefined

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

+0

爲什麼setTimeout? – cfs

+0

我不知道我想它會給它時間分配值?只是一個微弱的嘗試。無論是否存在,都會發生同樣的事情。 – CaitlinHavener

+1

不知道它是否與問題有關,但是您似乎認爲javascript已經爲您的變量阻塞了範圍,[它沒有](http://stackoverflow.com/questions/12645073/java-vs -javascript-可變範圍)。 – jbabey

回答

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塊計算它

+0

你指出我正確的方向!將該塊更改爲if(qty CaitlinHavener

+0

@CaitlinHavener很高興幫助你:) –

0

我想,在for產生太多的請求到服務器。因此,服務器響應可能不是200.您應該查找jQuery.ajax的屬性error,然後捕獲響應,然後您嘗試將setTimeout(...) ...移動到error部分。

+1

如果它導致錯誤,成功回調將不會發生,未定義將不會記錄到控制檯。 –