【发布时间】:2020-06-06 15:23:01
【问题描述】:
我正在使用 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 id="quantity-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>
Ajax 请求:
$("#quantity").change(function(){
const classname = document.querySelectorAll('#quantity')
Array.from(classname).forEach(function(element) {
console.log(element);
let id = element.getAttribute('data-id')
axios.patch(`/panier/${id}`, {
quantity: this.value
})
.then(function (response) {
// console.log(response);
console.log("refresh");
$("#table-shoppingcart").load(location.href + " #table-shoppingcart");
})
.catch(function (error) {
console.log("erreur");
// console.log(error);
});
})
});
我需要在我的控制器中获取数量,所以我尝试:
public function update(Request $request)
{
$data = $request->json()->all();
Log::info($data);
return response()->json(['success' => 'Cart Quantity Has Been Updated']);
}
但是当我尝试获取 $data 值时,我的数组在我的日志中是空的:
[2020-02-22 10:49:46] local.INFO: array ()
我试图改变:
$data = $request->json()->all();
到
$data = $request->all();
但同样的问题。
你有什么想法吗?
谢谢!
【问题讨论】:
-
能否请您添加您的路线文件?
-
哦,是的,对不起!完成了
-
我认为因为
axios.patch现在工作正常,所以请参考stackoverflow.com/questions/51170564/… -
我试过了。同样的错误,但我在我的数组中看到 row_method 但不是数量。所以我尝试将数量:this.value 更改为数量:5 进行测试。我现在得到了行数。所以这个问题是 ajax 请求中的数量:this.value。你有什么想法吗?
-
this指的是 JS 中的本地范围。因为您使用的是 Jquery,所以我看不出使用this的意义。您需要将事件注入到您更改功能中,然后您可以从那里获取值。让我知道您是否需要发布答案
标签: javascript php ajax laravel axios