我正在使用 laravel,现在,我正在制作一个用户注册表表单,我正在关联州及其城市,因此,我需要根据用户选择的州更改选择字段值。
我有一些形式:
{{ Form::select('city', $city, array('id', 'city')}}
如果我以常规方式使用 {{Form::select}} 字段,它会从一个州向所有城市收费,因此,当用户选择一个州时,它必须更改选择字段中的城市列表。
我搜索了但我没有找到任何东西。我怎样才能做到这一点?
谢谢。
您可以将 ajax 与 jQuery 一起使用。
在您的视图中设置状态更改时的事件,如下所示:
$(document).on('change', '#state_id', function (e) {
// empty the select with previous cities if we have.
$('#cities').empty();
$.ajax({
type: "POST",
dataType: "json",
// actions is a controller
// cities is a method of actions controller
url : "{{ URL::to('actions/cities') }}",
//here we set the data for the post based in our form
data : $('#MyFormID').serialize(),
success:function(data){
if(data.error === 0 ){ // all was ok
for (var i = 0; i < data.cities.length; i++) {
$('#cities').append("<option value='"+data.cities[i].id+"'>"+data.cities[i].city_name+"</option>")
}
}else{
alert(data);
}
},
timeout:10000
});
});
行动/城市控制器
//remember, this is a post method
public function postCities(){
// validate
$validator = Validator::make(Input::all(),
array(
'state_id' => 'required|integer'
));
if ($validator->fails()) {
return Response::json(array('error' => 1, 'message' => 'State is required'));
}
//City is your model, I assumes that you pkey is ID and the city name is city_name and your fkey is state_id
$cities = City::where('state_id', '=', Input::get('state_id'))->get();
return Response::json(array('error' => 0, 'cities' => $cities));
}
您可能想检查我的Laravel Cities包附带的示例 vue 组件,它完全执行您正在尝试构建的内容。
这是一个简单的包,允许您在本地播种世界上任何国家的所有城市(由 geonames.org 提供)并使用提供的 Eloquent 模型执行任何查询。它公开了一个 HTTP API 和一个 vue 组件,允许您通过一系列步骤选择任何城市。
您可以像任何其他输入字段一样将其插入表单中:
<form action="post-url" method="POST">
<geo-select></geo-select>
<!-- Add more form fields here... -->
<input type="submit">
</form>
使用提供的 Eloquent 模型,您可以执行如下查询:
// Get the States of USA in aplhabetic order
Geo::getCountry('US')
->children()
->orderBy('name')
->get();
抱歉,还没有演示,但你可以在github 页面上查看一些截图......
public function getCities($province_id)
{
$cities = Cities::where('province_id', '=', $province_id)->get(['id', 'name']);
return Response::json(array('error' => 0, 'cities' => $cities));
}