我使用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'
检查空响应,它可以正常工作。但是我不确定这是否是最好的方法。任何建议或指导,将不胜感激,谢谢
答案 0 :(得分:2)
如果找不到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
}
});