我有一个students_id的下拉列表。现在,当有人选择任何学生ID时,我想从另一个表中跟踪学生的姓名和班级。我使用ajax为此做了一些事情。它没有向我显示控制台中的任何错误,而只是给了我null数组,我认为那是与查询有关的问题。您可以在下面查看我的代码。 :)
//控制器
public function create()
{
$students = Student::pluck('student_id', 'id')->all();
return view('admin.reports.create', compact('students'));
}
public function reportsAjax(Request $request) {
$students = DB::table("students")->where("student_id", $request->student_id)->pluck("student_id","id");
return json_encode($students);
}
//视图和Ajax
<div class="form-group">
<label for="title">Select Student <span style="color: red">*</span></label>
<select name="student_id" class="form-control bg-dark text-white" >
<option>Select Student</option>
@foreach ($students as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
@endforeach
</select>
</div>
<div class="form-group">
<label class="control-label">Student Full Name <span style="color: red">*</span></label>
<input name="std_name" type="text" required class="form-control" />
</div>
<div class="form-group">
<label class="control-label">Class <span style="color: red">*</span></label>
<input name="std_class" type="text" required class="form-control" />
</div>
<script type="text/javascript">
$(document).ready(function() {
$('select[name="student_id"]').on('change', function() {
var studentInfo = $(this).val();
if(studentInfo) {
$.ajax({
url: '/reports/ajax/'+studentInfo,
type: "GET",
dataType: "json",
success:function(data) {
$('input[name="std_name"]').empty();
$.each(data, function(key, value) {
$('select[name="std_name"]').append('<input value="'+ key +'">'+ value +'/>');
});
}
});
}else{
$('select[name="std_name"]').empty();
}
});
});
</script>
//路线
Route::get('reports/ajax/{id}',array('as'=>'reports.ajax','uses'=>'ReportController@reportsAjax'));
Route::resource('admin/reports', 'ReportController', ['names'=>[
'index'=>'admin.reports.index',
'create'=>'admin.reports.create',
]]);
答案 0 :(得分:0)
尝试此查询:
public function create()
{
$students = Student::all()->only(['student_id', 'id']);
return view('admin.reports.create', compact('students'));
}
public function reportsAjax(Request $request)
{
$students = DB::table('students')->where('student_id', $request->student_id)->only(['student_id','id']);
return response()->json($students, 200);
}