我想从选择CHANTIER中填充选择的OUVRAGE,但是此代码无法正常工作,请问这是什么问题。
知道Ouvrage和Chantier hasMany之间存在关系
mois.blade.php
<div class="container">
<h1>Laravel 5.4 - Dynamic Dependant Select Example</h1>
{!! Form::open() !!}
<div class="form-group">
<label>Select Chantier:</label>
{!! Form::select('chantier_id',[''=>'--- Select Chantier ---']+$chantiers,null,['class'=>'form-control']) !!}
</div>
<div class="form-group">
<label>Select Ouvrage:</label>
{!! Form::select('ouvrage_id',[''=>'--- Select Ouvrage ---'],null,['class'=>'form-control']) !!}
</div>
<div class="form-group">
<button class="btn btn-success" type="submit">Submit</button>
</div>
{!! Form::close() !!}
</div>
javascript
<script type="text/javascript">
$("select[chantier='chantier_id']").change(function(){
var chantier_id = $(this).val();
var token = $("input[chantier='_token']").val();
$.ajax({
url: "<?php echo route('select-ajax') ?>",
method: 'POST',
data: {chantier_id:chantier_id, _token:token},
success: function(data) {
$("select[chantier='ouvrage_id'").html('');
$("select[chantier='ouvrage_id'").html(data.options);
}
});
});
</script>
ajax-select.blade.php
<option>--- Select Ouvrage ---</option>
@if(!empty($ouvrages))
@foreach($ouvrages as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
@endforeach
@endif
路线
Route::get('mois', 'SalarieController@mois');
Route::post('select-ajax', ['as'=>'select-ajax','uses'=>'SalarieController@selectAjax']);
我的控制器
public function mois()
{
$chantiers = DB::table('chantiers')->pluck("chantier","id")->all();
return view('salarie.mois',compact('chantiers'));
}
/**
* Show the application selectAjax.
*
* @return \Illuminate\Http\Response
*/
public function selectAjax(Request $request)
{
if($request->ajax()){
$ouvrages = DB::table('ouvrages')->where('chantier_id',$request->chantier_id)->pluck("ouvrage","id")->all();
$data = view('ajax-select',compact('ouvrages'))->render();
return response()->json(['options'=>$data]);
}
}