laravel - 从 Laravel 状态加载城市

标签 laravel load states city

我正在使用 laravel,现在,我正在制作一个用户注册表单,我正在关联州及其城市,因此,我需要根据用户选择的州更改选择字段值。

我有以下形式的内容:

{{ Form::select('city', $city, array('id', 'city')}}

如果我以传统方式使用 {{Form::select}} 字段,它会向一个州的所有城市收费,因此,当用户选择一个州时,它必须更改选择字段中的城市列表。

我搜索过,但没有找到。我怎样才能做到这一点?

谢谢。

最佳答案

您可以将 ajax 与 jQuery 结合使用。

在您的 View 中设置状态更改时的事件,如下所示:

$(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
        });                         
    });

行动/城市 Controller

//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 - 从 Laravel 状态加载城市,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26922123/

相关文章:

php - Carbon 解析日期格式

laravel - 更改 Laravel Migrations 的执行顺序

php - "Resource interpreted as Image but transferred with MIME type text/html"非常奇怪的问题

Java slick statebased game - 状态返回空点错误

php - Durandal 上的 BreezeJS 与 PHP REST API (Laravel)

java - 文件未正确保存

performance - Jmeter 性能测试 DOM 和加载时间

apache-flex - 如何使用mxml继承状态?

javascript - 在页面加载时调用 javascript

php - 验证更新排除某些字段