【发布时间】:2020-06-07 07:54:02
【问题描述】:
我正在使用 Laravel 制作购物车。
我有:
路线:
Route::post('/panier/ajouter', 'CartController@store')->name('cart.store');
Route::patch('/panier/{product}', 'CartController@update')->name('cart.update');
查看:
<table class="table" id="table-shoppingcart">
<thead>
<tr>
<th class="text-center" id="item-title-shoppingcart"></th>
<th class="text-center" id="size-title-shoppingcart">Taille</th>
<th class="text-center" id="quantity-title-shoppingcart">Quantité</th>
<th class="text-center" id="price-title-shoppingcart">Prix</th>
{{-- <th class="text-center" id="delete-title-shoppingcart"></th> --}}
</tr>
</thead>
<tbody>
@foreach (Cart::content() as $product)
<tr>
<th><img class="text-center item-content-shoppingcart" src="{{ $product->model->image }}"></th>
<td class="text-center td-table-shoppingcart size-content-shoppingcart">S</td>
<td class="td-table-shoppingcart quantity-content-shoppingcart">
<select name="quantity" class="custom-select text-center quantity" id="quantity" data-id="{{ $product->rowId }}">
@for ($i = 0; $i < 5 + 1 ; $i++)
<option {{ $product->qty == $i ? 'selected' : '' }}>{{ $i }}</option>
@endfor
</select>
</td>
<td class="text-center td-table-shoppingcart price-content-shoppingcart">{{ getPrice($product->subtotal()) }}</td>
</tr>
@endforeach
</tbody>
</table>
阿贾克斯
$('body').on('change','#quantity',function(){
var quantityvalue = this.value;
var classname = document.querySelectorAll('#quantity')
Array.from(classname).forEach(function(element) {
console.log(element);
var id = element.getAttribute('data-id')
axios.post(`/panier/${id}`, {
quantity: quantityvalue,
_method: 'patch'
})
.then(function (response) {
// console.log(response);
console.log("refresh");
$("#refresh").load(location.href + " #refresh");
$("#refresh2").load(location.href + " #refresh2");
})
.catch(function (error) {
console.log("erreur");
// console.log(error);
});
})
});
控制器
public function update(Request $request, $rowId)
{
$data = $request->json()->all();
$validator = Validator::make($request->all(), [
'quantity' => 'required|numeric|between:0,5'
]);
Log::info($data);
if($validator->fails()) {
Session::flash('error', 'La quantité du produit ne doit pas dépasser 5.');
return response()->json(['error' => 'Cart Quantity Has Not Been Updated']);
}
if( $data['quantity'] == 0){
Cart::remove($rowId);
}
else {
Cart::update($rowId, $data['quantity']);
}
Session::flash('danger', 'La quantité du produit est passée à ' . $data['quantity'] . '.');
return response()->json(['success' => 'Cart Quantity Has Been Updated']);
}
问题是当我的购物篮中有几种不同的产品时:
例如,如果我想改变我的产品 1 的数量,它也会改变我的产品 2 的数量,具有相同的值。
如何将更新与每个选定的更新分开?
【问题讨论】:
标签: javascript jquery ajax laravel axios