gpt4 book ai didi

javascript - 如何检查 laravel Controller 的 ajax 响应是否为空?

转载 作者:行者123 更新时间:2023-12-01 00:48:24 24 4
gpt4 key购买 nike

我使用 ajax 从事 Laravel 项目。下面是我的 Controller 。

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
}
});

关于javascript - 如何检查 laravel Controller 的 ajax 响应是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57195119/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com