在 laravel 中实现 Jquery ajax get request



我更像是一个棱角分明的人,所以我对jquery不太好。我有一个从某人那里接手的项目,我必须对我的控制器实现一个 get 请求并附加返回的数据以查看。我知道这很模糊,但我会感谢任何帮助。

<tbody>
@foreach($restaurant_meals as $meal)
<tr>
<td>
{{$meal->name}}
</td>
<td>
${{$meal->price}}
</td>
<td>
<a href=""><i class="fa fa-plus-circle"></i></a>
</td>
</tr>
@endforeach
</tbody>

这是我的看法。 这是我的 ajax 请求。

<script type="text/javascript">
$(documnent).ready(function(){
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/addtocartid' + id, // This is the url we gave in the route
data: {'id' : id}, // a JSON object to send back
success: function(response){ // What to do if we succeed
console.log(response); 
}
});
});

那么我的控制器将是

public function getaddtoCart(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);
return redirect()->route('home');
}

任何帮助将不胜感激

您的问题在于 URL 中id的串联。它正在 URL 模式中添加额外的数字。

$(documnent).ready(function(){
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/addtocartid', // This is the url we gave in the route
data: {'id' : id}, // a JSON object to send back
success: function(response){ // What to do if we succeed
console.log(response); 
}
});
});

喜欢/addtocartid1而不是/addtocartid/1

理想情况下,应该将其删除。您已经通过data属性发送参数

最新更新