【发布时间】:2019-12-05 02:14:26
【问题描述】:
我正在尝试通过 ajax 提交数据(添加到购物车),但在控制台 POST http://localhost/glutax9gs/cartupdate500(内部服务器错误)中出现错误
我的代码有什么问题?是javascript还是控制器?
这是我的路线:
Route::get('/cartupdate', 'FrontEndController@cartupdate')->name('update.cart');
Route::post('/cartupdate', 'FrontEndController@cartupdate')->name('cart.update');
控制器代码在这里:
public function cartupdate(Request $request)
{
if ($request->isMethod('post')){
if (empty(Session::get('uniqueid'))){
$cart = new Cart;
$cart->fill($request->all());
Session::put('uniqueid', $request->uniqueid);
$cart->save();
}else{
$cart = Cart::where('uniqueid',$request->uniqueid)
->where('product',$request->product)->first();
//$carts = Cart::where('uniqueid',$request->uniqueid)
//->where('product',$request->product)->count();
if (count($cart) > 0 ){
$data = $request->all();
$cart->update($data);
}else{
$cart = new Cart;
$cart->fill($request->all());
$cart->save();
}
}
return response()->json(['response' => 'Successfully Added to Cart.','product' => $request->product]);
}
$getcart = Cart::where('uniqueid',Session::get('uniqueid'))->get();
return response()->json(['response' => $getcart]);
}
jQuery 代码在这里:
$(".to-cart").click(function(){
var formData = $(this).parents('form:first').serializeArray();
$.ajax({
type: "POST",
url: '{{route("cart.update")}}',
data:formData,
success: function (data) {
getCart();
$.notify(data.response, "success");
},
error: function (data) {
console.log('Error:', data);
}
});
});
查看代码在这里:
<form>
<p>
{{csrf_field()}}
@if(Session::has('uniqueid'))
<input type="hidden" name="uniqueid" value="{{Session::get('uniqueid')}}">
@else
<input type="hidden" name="uniqueid" value="{{str_random(7)}}">
@endif
<input type="hidden" name="title" value="{{$product->title}}">
<input type="hidden" name="product" value="{{$product->id}}">
<input type="hidden" id="cost" name="cost" value="{{$product->price}}">
<input type="hidden" id="quantity" name="quantity" value="1">
@if($product->stock != 0 || $product->stock === null )
<button type="button" class="button style-10 to-cart">Add to cart</button>
@else
<button type="button" class="button style-10 to-cart" disabled>Out Of Stock</button>
@endif
{{--<button type="button" class="button style-10 hidden-sm to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</button>--}}
</p>
</form>
【问题讨论】:
-
在你的 laravel 日志中没有任何用处?
-
检查您在
storage/logs中的日志,或检查服务器错误日志。 500 错误是一个非常普遍的错误,并不能解释发生了什么问题。 -
我在 Laravel.log #50 D:\xampp\htdocs\glutax9gs\project\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(116) 中收到此错误: Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request)) #51 D:\xampp\htdocs\glutax9gs\index.php(53): Illuminate\Foundation\Http\Kernel->handle(Object (Illuminate\Http\Request)) #52 {main}
-
这只是堆栈跟踪的一小部分。您正在寻找确切的错误。
-
创建
Cart对象的方式打破了DI 和MVC 模式。最好将此工作委托给不同的类(而不是控制器),并根据情况使用Cart::firstOrCreate或Cart::create之类的东西。
标签: php jquery ajax laravel laravel-5