ajax - Laravel Ajax 使用选择选项更新购物车中的项目
问题描述
我想用一个选择选项来更新我的购物车中的商品数量,所以当我的购物车中有两个或更多产品时,当我尝试更改其中一个数量项目的产品时,我的购物车中的每个产品都会更新为我发送的相同信息。
HTML 选择选项
<select class="select quantity" detail-id="{{ $detail->id }}" product-id="{{ $detail->product->id }}" product-type="{{ $detail->type }}">
@php
if($detail->type == 'Unidad' || $detail->type == 'Unit' || $detail->type == 'Einheit'){
$limit = $detail->product->unit_stock;
} else if($detail->type == 'Caja' || $detail->type == 'Box'){
$limit = floor($detail->product->unit_stock / $detail->product->pcs_box);
}
@endphp
@for($i = 0; $i <= $limit; $i++)
<option value="{{ $i }}" {{ $i == $detail->quantity ? 'selected' : '' }}> {{ $i }} </option>
@endfor
</select>
AJAX
$('.quantity').change(function () {
var productId = $(this).attr('product-id');
var cartDetail = $(this).attr('detail-id');
var productType = $(this).attr('product-type');
var productQty = $(this).find(':selected').index();
// console.log(productId);
// console.log(cartDetail);
// console.log(productType);
// console.log(productQty);
loadItemCart(productId, cartDetail, productType, productQty);
});
function loadItemCart(productId, cartDetail, productType, productQty){
$.ajax({
method: 'POST',
url: '/cart-qty',
data: {
detail: cartDetail,
type: productType,
product: productId,
quantity: productQty,
},
success: function (res) {
if(res.status == 'success'){
toastr.success(res.message);
window.setTimeout(function(){location.reload()},1500)
}
if(res.status == 'error'){
toastr.error(res.message);
window.setTimeout(function(){location.reload()},1500)
}
}
});
}
控制器
public function cartQty(Request $request)
{
$cartDetail = CartDetail::where([
['cart_id', auth()->user()->cart->id],
['id', $request->detail],
['product_id', $request->product]
])->firstOrFail();
...
}
解决方案
推荐阅读
- mamp - Mac 上的证书链文件在哪里?(MAMP Pro 5.0.1)
- php - 如果空白 HTML/PHP 选择默认选项
- ios - CoreTelephony 在不需要的通信扩展中调用时返回 nil
- android - 在我移动时绘制一条折线
- sapui5 - Ui5 的 Component.js 中带有 2 个路径(颜色)的图标
- amazon-web-services - 如何为生产设置 AWS RDS 实例,以便我可以定期从我的个人计算机中读取自定义数据
- python - 在 read() 之前或之后删除空行
- ios - 从阴影按钮中删除标题阴影
- python - The if-statement is triggered no matter the input
- android - 没有与@ContributesAndroidInjector 绑定的注入器工厂