首页 > 解决方案 > Ajax,旧值先出现,然后新值出现

问题描述

我有 Session::flash 通知(引导 toasts),用于通知将产品添加到购物车:

@if(Session::has('add-product'))
<div aria-live="polite" aria-atomic="true" class="d-flex justify-content-center align-items-center">
 <div class="toast fixed-top" role="alert" aria-live="assertive" aria-atomic="true" data-delay="3000">
  <div class="toast-header bg-success">
   <span class="mr-auto notif_text"></span>
   <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
    <span aria-hidden="true">&times;</span>
   </button>
  </div>
 </div>
</div>
@endif

CartController 与 Session:flash:

public function addCart(Request $request, $id){
    $product = Product::find($id);
    $oldCart = Session::has('cart') ? Session::get('cart') : NULL;
    $cart = new Cart($oldCart);
    $cart->add($product, $product->id);

    $request = Session::put('cart', $cart);

    Session::flash('add-product', $product->name);

    return response()->json([
         'total_quantity' => Session::has('cart') ? Session::get('cart')->totalQty : '0',
         'notif_text' => 'Product' . Session::get('add-product', $product->name) . 'added to cart'
     ]);
  }

和 Ajax 请求:

$(document).ready(function() {
  $('.product-icon-container').find('.ajaxcartadd').click(function(event) {
    event.preventDefault();
    $('.toast').toast('show');
    $.ajax({
      url: $(this).attr('href'),
      dataType: 'JSON',
      success: function(response) {
        $('.prodcount').html(response.total_quantity);
        $('.notif_text').html(response.notif_text); //!!!Here I load the notification text!!
      }
    });
    return false;
  });
});

我的问题是如何确保不出现旧值,而是立即出现新值。

现在它像这样工作: img_1

然后大约 1 秒后出现一个新通知: img_2

如何解决这个问题?

标签: htmljqueryajaxlaravel

解决方案


首先像这样删除已经分配的值,然后将值分配给该类元素。

document.getElementsByClassName("prodcount").innerHTML = ""; // or $('.prodcount').innerHTML = "";
document.getElementsByClassName("notif_text").innerHTML = ""; // or $('.notif_text').innerHTML = "";
$('.prodcount').html(response.total_quantity);
$('.notif_text').html(response.notif_text);

推荐阅读