我正在尝试使用第一个下拉菜单的数据来填充第二个下拉菜单。 这里的一个例子: https://gitlab.com/Bons/laravel5.3_dynamic_dropdown/blob/master/readme.md
控制器功能返回数据,但第二个下拉列表为空。
第一个下拉列表:
<span>Country: </span>
<select style="width: 200px" class="country" id="id_country">
<option value="0" disabled="true" selected="true">-Select-</option>
@foreach($countries as $contry)
<option value="{{$contry->id_country}}">{{$contry->name}}</option>
@endforeach
</select>
链接的下拉列表:
<label>City
<select id="region" class="form-control input-sm" name="region_id">
<option value=""></option>
</select>
</label>
脚本:
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','.country',function(){
console.log("hmm its change");
var id=$(this).val();
console.log(id)
$.ajax({
type:'get',
url:'{!!URL::to('findRegions')!!}',
data:{'id':id},
success:function(data) {
console.log("success");
console.log(data.length);
console.log(data);
$.each(data, function(index,subCatObj){
// console.log(subCatObj.name)
$('#region').append(''+subCatObj.name+'');
});
},
error:function(){
console.log("error");
}
});
});
});
</script>
路线:
Route::get('/findRegions/','GirlsController@findRegions');
控制器功能:
public function findRegions(Request $request){
$id=$request->id;
$regions=Region::select('name')
->where('id_country',$id)
->get();
dump($regions);
return $regions;
}
答案 0 :(得分:0)
这是我的做法, 在routes / web.php中
2018-08-16 15:04:17
在Controller中:Main.php
Route::post('select-ajax', 'Main@selectAjax')->name('select-ajax');
然后创建一个简单的刀片文件名称ajax-select.blade.php
public function __construct()
{
View::share('selectAllCountries', Country::pluck("name","id")->all());
}
public function selectAjax(Request $request)
{
if($request->ajax())
{
$getRegion = Region::where('id_country',$request->id)->pluck("nameOfTheRegion","id")->all();
$data = view('ajax-select',compact('getRegion'))->render();
return response()->json(['options'=>$data]);
}
}
Ajax调用
<option selected disabled>--- Select Region---</option>
@if(!empty($getRegion))
@foreach($getRegion as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
@endforeach
@endif
希望这会有所帮助