[英]how to get success or failure response from controller to ajax in laravel?
[英]How to check ajax's response from laravel's controller is empty?
我使用Ajax從事laravel項目。 以下是我的控制器。
public function Student(Request $request){
$student = Student::where('school_uuid',$request->school_uuid)
->where('cardid',$request->cardid)
->first();
return response()->json($student);
}
這是我的ajax。
$.ajax({
url:"{{ route('api.student') }}",
method:"POST",
data:{
cardid:cardid,
school_uuid:"{{$shareuser->school_uuid}}",
},
success:function(response){
if (typeof response.name !== 'undefined'){
console.log(response.name);
}else{
console.log("no data");
}
}
});
我可以使用typeof response.name !== 'undefined'
檢查空響應,並且可以正常工作。 但是我不確定這是否是最好的方法。 任何建議或指導對此將不勝感激,謝謝
如果找不到該student
則應該發送正確的響應代碼,然后在javascript中進行處理。
例如:
public function Student(Request $request){
$student = Student::where('school_uuid',$request->school_uuid)
->where('cardid',$request->cardid)
->firstOrFail(); // This will cause a 404 if the student does not exist
return response()->json($student);
}
然后在您的JS中:
$.ajax({
url:"{{ route('api.student') }}",
method:"POST",
data:{
cardid:cardid,
school_uuid:"{{$shareuser->school_uuid}}",
},
success:function(response){
console.log(response.name);
},
error: function(xhr) {
if (xhr.status === 404) {
// Handle 404 error
}
// Handle any other error
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.