html - 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">×</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
如何解决这个问题?
解决方案
首先像这样删除已经分配的值,然后将值分配给该类元素。
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);
推荐阅读
- node.js - Query.user 的类型必须是输出类型但得到:未定义
- c - 如何在没有makefile的情况下链接不同目录中的对象?
- javascript - 如何使用 Javascript 访问链接?
- stata - 显示完整的变量名
- r - 带约束的分段线性回归 - r
- javascript - 在 Angular 中进行错误处理的对象对象
- html - 无法为 R 中的 rvest 选择悬停弹出文本
- ios - 滚动 UITableView 期间计时器将重置并停止运行
- package - 尽管 pylint 似乎已安装,但“找不到命令”
- vb.net - 打开/关闭操作等效 VB6 / VB.NET