繁体   English   中英

在ajax调用后更新javascript变量

[英]Update javascript variables after ajax call

在尝试通过ajax更新购物车后,我试图动态更新通知。 我似乎无法弄清楚如何重新更新所有变量,以便计算循环可以再次运行。 我尝试将if语句包装到一个函数中,然后在updated_wc_div中再次调用它,但这没有用。

有什么建议么?

( function($) { 
  var membership_price = membership.price;
  //grab cart total from html
  var total = parseInt($('.order-total .woocommerce-Price-amount').text().replace('$',''));
  compared_price = parseInt(membership_price) - total;

  //everything runs fine on load.

  if ( total < membership_price ) {
    message = 'For <strong>$'+ compared_price +'</strong> more, gain access to unlimited downloads. <a href="/series/unlimited-membership">Become a member!</a>';
    notice = '<div class="woocommerce-info">' + message + '</div>';
    $('.woocommerce-notices-wrapper').html(notice);
  }
  //running this to know when ajax is called
  $(document.body).on('updated_wc_div',function( event ){
    $('.woocommerce-notices-wrapper').empty();
    total = parseInt($('.order-total .woocommerce-Price-amount').text().replace('$',''));
    //I believe problem is here, it doesn't update variable so it could loop again.
  });

} )(jQuery);

这是我在调用ajax调用后动态更新对象的方式:

 function getCart(user_id) { $.ajax({ type: "POST", url: "get_total_cart.php", data: { 'user_id': <?php echo $user_id; ?> }, beforeSend: function() {}, success: function(response) { var user = JSON.parse(response); var total_cart = parseInt(user.total_cart); $("#total_cart").html(total_cart); } }); } function addCart(product_id, user_id) { $.ajax({ type: "POST", url: "add_cart.php", data: { 'product_id': product_id, 'user_id': user_id }, beforeSend: function() {}, success: function(response) { getCart(user_id); } }); } $(document).ready(function() { $(".se-pre-con").fadeOut("slow"); getCart(<?php echo $user_id; ?>); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="total_cart">Total Cart</div> <input type="button" name="add_cart" id="add_cart" value="Add to Cart" onclick="addCart('<?php echo $product[id]; ?>', '<?php echo $user_id; ?>')" class="btn btn-info"> 

我希望这有帮助。 干杯。

只需将函数放在ajax函数内部或使ajax函数“ async:false”

 $.ajax({ type: "POST", url: "", async:false, // <======== remove asynchronous property data: {}, success: function(result) { } }); //////////////////////////////////////////////// $.ajax({ type: "POST", url: "", data: {}, success: function(result) { // Or put your function here } }); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM