weixin_33674976 2017-10-26 15:31 采纳率: 0%
浏览 26

用AJAX调用函数

I'm not sure how to explain this completely, but I hope this will make sense.

I have a function that I've made that calculates the remaining amount to spend to qualify for free delivery when the basket value total falls within certain thresholds.

The basket value is updated with AJAX every time a product is added to the basket.

The add to basket button appears in an AJAX generated modal.

I need my function to be called on every page refresh and also every time a product is added to the basket when the AJAX generated add to basket button is clicked. I'm trying to do all of this with the below, but it doesn't seem to work correctly. One of the problems is that the event fires multiple times when the add to basket button is clicked and another is that the basket total is updated after the event and so the total isn't calculated correctly.

Can anyone explain how I would tidy all off this up?

function totalBag() {
   var standardDeliveryLow = 49.99;
   var standardDeliveryHigh = 64.99;
   var expressDeliveryLow = 65.00;
   var expressDeliveryHigh = 99.99;
   var bagValue = $('#basket-value').text();
   var bagTotal = Number(bagValue.replace(/[^0-9\.-]+/g,""));

   if (bagTotal >= standardDeliveryLow && bagTotal <= standardDeliveryHigh) {
       var standardDifference = parseFloat(Math.round((standardDeliveryHigh - bagTotal) * 100) / 100).toFixed(2);
       $('<div class="delivery-message"><p>£'+ standardDifference +' from standar delivery</p></div>').insertAfter('.breadcrumbs');
   } else if (bagTotal >= expressDeliveryLow && bagTotal <= expressDeliveryHigh) {
      var expressDifference = parseFloat(Math.round((expressDeliveryHigh - bagTotal) * 100) / 100).toFixed(2); 
      $('<div class="delivery-message"><p>£'+ expressDifference + ' from express delivery</p></div>').insertAfter('.breadcrumbs');
   } else {
     return false;
   }
}

$(document).on('ajaxSuccess', function(e) { 
  $('[name="AddItemToBasket"]').on('click', function() {
    $('body').bind('ajaxSuccess.custom', function() {
     totalBag();
     //alert('this works');
     $(this).unbind('ajaxSuccess');
  });
 });
});


totalBag();
  • 写回答

1条回答 默认 最新

  • 乱世@小熊 2017-10-26 19:55
    关注

    EDIT: Have fixed the issue where text was duplicating. Also have added comments for more understanding.


    Had a check at the link you specified and tried the following modified code.

    As per @ADyson, have removed the click event, which is fixing the multiple event firing.

    Regarding your other problem, the total is updated after the event, yes the HTML is getting updated after the ajaxSuccess is triggered. Hence have used the ajaxSuccess event itself to get the basket amount and use it in totalBag fn.

    It seems to be working. Kindly confirm:

    //Adding empty div so that we can just update the value later
    $(document).on('ready', function(){
        $('<div class="delivery-message"></div>').insertAfter('.breadcrumbs');
    })
    
    function totalBag(bagTotal) {
       var standardDeliveryLow = 49.99;
       var standardDeliveryHigh = 64.99;
       var expressDeliveryLow = 65.00;
       var expressDeliveryHigh = 99.99;
       //var bagValue = $('#basket-value').text();
       //var bagTotal = Number(bagValue.replace(/[^0-9\.-]+/g,""));
    
       //Using a variable to store the calculated amount with text
       var innerHTML = "";
       if (bagTotal >= standardDeliveryLow && bagTotal <= standardDeliveryHigh) {
           var standardDifference = parseFloat(Math.round((standardDeliveryHigh - bagTotal) * 100) / 100).toFixed(2);
           innerHTML= "<p>£"+ standardDifference +" from standar delivery</p>";
       } else if (bagTotal >= expressDeliveryLow && bagTotal <= expressDeliveryHigh) {
          var expressDifference = parseFloat(Math.round((expressDeliveryHigh - bagTotal) * 100) / 100).toFixed(2); 
          innerHTML= "<p>£"+ expressDifference +" from express delivery</p>";
       } else {
         return false;
       }
       //Updating the placeholder with new contents
       $(".delivery-message").html(innerHTML);
    }
    
    //Gets triggered after every Ajax Success.
    //e -> event object, xhr -> The Ajax object which has request and response details, 
    //settings -> The settings we used to trigger Ajax, including the request URL
    $(document).on('ajaxSuccess', function(e, xhr, settings) { 
        //Checking if the request is of Adding Item to Basket
        if(settings.url.indexOf("AddItemToBasket") !== -1){
            //Getting the response and parsing it
            var resp = xhr.responseText;
            var respObj = JSON.parse(resp);
            //Checking if response is success i.e., item added to cart successfully
            if(respObj.success){
                //Getting the updated Basket value and calling totalBag
                var bagTotal = respObj.basket.subTotal;
                totalBag(bagTotal); 
            }       
        }
    
    });
    totalBag(0);
    
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮