如何使用jquery,ajax和laravel创建依赖下拉列表?
路线:
Route::get('get-study-programs/{faculties_id}', 'DisciplinaryResearchesController@getStudyPrograms');
查看:
<div class="form-group {!! $errors->has('faculties_id') ? 'has-error' : '' !!}">
{!! Form::label('faculties_id', 'Faculty', ['class' => 'col-md-2 control-label']) !!}
<div class="col-md-6">
{!! Form::select('faculties_id', \App\Faculty::pluck('name','id'), null,
['class' => 'js-selectize', 'placeholder' => 'Choose']) !!}
<strong>{!! $errors->first('faculties_id', '<p class="help-block">:message</p>') !!}</strong>
</div>
<div class="form-group {!! $errors->has('study_program_id') ? 'has-error' : '' !!}">
{!! Form::label('study_program_id', 'Study Program', ['class' => 'col-md-2 control-label']) !!}
<div class="col-md-6">
{!! Form::select('study_program_id', [], null,
['class' => 'js-selectize', 'placeholder' => 'Choose']) !!}
<strong>{!! $errors->first('study_program_id', '<p class="help-block">:message</p>') !!}</strong>
</div>
控制器:
public function create()
{
$listFaculties = Faculty::lists('name', 'id');
return view('disciplinary_researches.create', compact('listFaculties'));
}
public function getStudyPrograms($faculties_id)
{
$studyPrograms = StudyProgram::where('faculties_id', $faculties_id)->pluck('name', 'id');
$list = '';
foreach ($studyPrograms as $key => $value) {
$list .= "<option value='" . $key . "'>" . $value . "</option>";
}
return $list;
}
JavaScript:
<script type="text/javascript">
$('#faculties_id').on('change', function () {
getStudyPrograms($(this).val());
});
function getStudyPrograms(faculties_id) {
$.get('{{ url('/get-study-programs')}}/'+faculties_id, function (data) {
$("#study_program_id").html(data);
});
}
$(document).ready(function () {
getStudyPrograms($('#faculties_id').val());
});
但是运行上面的代码时,我在GET http: // localhost / get-study-programs 404 (Not Found)
中发现错误,这是原始网址http://localhost/lab/public/disciplinary-research/create
,在我上面的代码编写中出了什么问题?
感谢您的回答,这非常有帮助
答案 0 :(得分:0)
您已经使用必需的参数声明了路由,但是在您的示例中,您没有在参数中传递ID。
如果您认为该参数可以是可选的,则可以如下所示定义路由。
Route::get('get-study-programs/{faculties_id?}', 'DisciplinaryResearchesController@getStudyPrograms');
因此,您将能够访问这两个路径:
http://localhost/get-study-programs
和
http://localhost/get-study-programs/1
编辑:
我还认为,下面的方法可以为您提供@Agus:
路线:
Route::get('faculties', 'DisciplinaryResearchesController@create');
Route::get('get-study-programs/{faculties_id?}', 'DisciplinaryResearchesController@getStudyPrograms');
控制器(代替创建模型,我使用了示例数组):
public function create()
{
$listFaculties = [
[
"name1" => 1
],
[
"name2" => 2
],
[
"name3" => 3
]
];
return view('dr', $listFaculties);
}
public function getStudyPrograms($faculties_id="")
{
$studyPrograms = [["name" => "name".rand(0, 100), "id" => 1], ["name" => "name".rand(0, 100), "id" => 2]];
$list = '';
foreach ($studyPrograms as $key => $value) {
$list .= "<option value='" . $value['id'] . "'>" . $value['name'] . "</option>";
}
return $list;
}
视图文件和JS代码将与您发布时的样子一样,并且AJAX对我来说很好。
谢谢。