大家好。在我的laravel应用程序中,我正在尝试检查我的表中是否存在对特定日期,主题,成绩的关注。如果是这样,我有一个if statement
设置,根据返回的内容显示欲望结果。
我正在使用ajax发出请求,但似乎ajax继续运行错误函数,我似乎没有得到任何错误代码或internal server error(500, 404, 403, etc)
在我的控制台中,状态返回为{{1} }
这是我的剧本:
200 ok
以下是请求发送到的控制器:
$(document).on('change', '#subject', function(event) {
event.preventDefault();
/* Act on the event */
var subject = $('#subject').val();
var grade = $('#grade').val();
var date = $('#date').val();
if (subject != "" && grade != "") {
$.ajax({
url:"/attendence/students",
method:"GET",
data:{"subject_id":subject, "grade_id":grade, "date":date},
dataType:"json",
success:function(data){
$("#result").html(data);
},
error:function(){
$("#result").html('There was an error please contact administrator');
}
});
}
});
现在,如果此代码返回true:
public function students(Request $request)
{
//
$grade = Grade::findOrFail($request->grade_id);
$subject = Subject::findOrFail($request->subject_id);
$students = Student::where('grade_id', $grade->id)->get(['id', 'first_name','middle_name', 'surname', 'grade_id']);
$statuses = Attendence::statuses();
// this check if attendence has been setup for the given date.
// if so prevent user for enter another date
$attendenceExists = Attendence::where([
'grade_id' => $grade->id,
'subject_id' => $subject->id,
'date' => $request->date
])->first();
if ($attendenceExists) {
return response()->json('A recorded attendence already exists for the seleced grade and subject!');
}
else {
return \View::make('attendence.partials.attendence-form')->with(array(
'students' => $students,
'subject' => $subject,
'date' => $request->date,
'statuses' => $statuses
));
}
}
此处运行的条件会返回正确的结果。但是我上面的// this check if attendence has been setup for the given date.
// if so prevent user for enter another date
$attendenceExists = Attendence::where([
'grade_id' => $grade->id,
'subject_id' => $subject->id,
'date' => $request->date
])->first();
if ($attendenceExists) {
return response()->json('A recorded attendence already exists for the seleced grade and subject!');
}
确实运行但是我得不到正确的结果。这是我得到的结果:
发生错误请联系管理员
这表明正在运行的是ajax请求的这一部分:
else statement
令人惊讶的是,当我检查控制台时,这就是我所看到的:
这正是我想要的,但是否则会返回ajax。我做错了吗?
答案 0 :(得分:3)
当您返回dataType
时,json
设置为html
。将其更改为html
。
答案 1 :(得分:2)
$.ajax({
url:"/attendence/students",
method:"GET",
data:{"subject_id":subject, "grade_id":grade, "date":date},
dataType:"json",
statusCode: {
200: function(data) {
$("#result").html(data.responseText);
};
}
}
});
试试这个。我希望这会对你有所帮助
答案 2 :(得分:0)
我想说根本不要设置数据类型。只需完全删除该设置,让 jQuery ajax() 方法为您自动检测它。这样,如果响应类型是 JSON,它就会起作用。如果响应类型是 HTML,它也可以工作。 ??