这是我的控制器代码 公共函数 add_cart(请求 $request , $id) {
// Validate the request if needed
if (Auth::guard('customer')->check()) {
$product = Product::find($id);
if (!$product) {
return response()->json(['message' => 'Product not found'], 404);
}
$product = Product::find($id);
$user = Auth::guard('customer')->user();
$add_cart = new Cart;
$add_cart->product_id = $product->id;
$add_cart->user_id = $user->id;
$add_cart->quantity = $request->quantity;
$add_cart->save();
return response()->json(['message' => 'Product added to cart']);
}
else {
return view('auth.customer_login');
}
{"message":"产品已添加到购物车"} 此消息是在添加产品后显示的,但我只想看到添加与新产品添加相同的页面
请添加条件检查其 ajax 请求。
public function add_cart(Request $request , $id) {
// Validate the request if needed
if (Auth::guard('customer')->check()&& $request->ajax()) {
$product = Product::find($id);
if (!$product) {
return response()->json(['message' => 'Product not found'], 404);
}
$product = Product::find($id);
$user = Auth::guard('customer')->user();
$add_cart = new Cart;
$add_cart->product_id = $product->id;
$add_cart->user_id = $user->id;
$add_cart->quantity = $request->quantity;
$add_cart->save();
return response()->json(['message' => 'Product added to cart']);
}
else {
return view('auth.customer_login');
}
}
添加路线
应用程序/Http/routes.php
Route::get('/add_cart/{id}','AjaxController@add_cart');
现在我们的观点
<html>
<head>
<title>Ajax Example</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script>
function add_cart() {
$.ajax({
type:'get',
url:'/add_cart/' +id,
data:'_token = <?php echo csrf_token() ?>',
success:function(data) {
$("#msg").html(data.message);
}
});
}
</script>
</head>
<body>
<div id="msg"></div>
<div id = 'product'>This message will be replaced using Ajax.
Click the button to replace the message.</div>
<?php
echo Form::button('add To Cart',['onClick'=>'add_cart()']);
?>
</body>
</html>