简体   繁体   English

Laravel / Javascript:在选择了不同的选择/下拉列表后填充选择/下拉列表

[英]Laravel/Javascript: populate a select/dropdown after a different select/dropdown is selected

I'm looking for a solution to populate a dropdown/select (eg called dropdown 2) upon selecting an option from another dropdown (eg dropdown 1). 我正在寻找一个解决方案,在从另一个下拉列表中选择一个选项(例如下拉列表1)时填充下拉列表/选择(例如,称为下拉列表2)。

For example, selecting Toyota from dropdown 1 will then populate dropdown 2 with the models of a toyota eg Corolla, Camry etc. Or another example - picking a country in one dropdown will populate the different cities of that country in another dropdown. 例如,从下拉列表1中选择丰田将使用丰田(例如卡罗拉,凯美瑞等)的模型填充下拉列表2.或者另一个例子 - 在一个下拉列表中选择一个国家将在另一个下拉列表中填充该国家的不同城市。

I'm using laravel as my framework, so it's important my solution (a) works within laravel and (b) grabs the results from a mysql database, not just a hardcoded array of values. 我使用laravel作为我的框架,所以重要的是我的解决方案(a)在laravel中工作,(b)从mysql数据库获取结果,而不仅仅是硬编码的数组。

I have tried to implement a solution from this post here: http://forums.laravel.io/viewtopic.php?pid=40028 我试图在这里发布一个解决方案: http//forums.laravel.io/viewtopic.php?pid = 40028

But it's not working within my setup. 但它在我的设置中不起作用。 This is what I have: 这就是我所拥有的:

My view looks like this: 我的观点如下:

{{ Form::open() }}
    <select id="make" name="make">
        <option>Select Car Make</option>
        <option value="1">Toyota</option>
        <option value="2">Honda</option>
        <option value="3">Mercedes</option>
    </select>
    <br>
    <select id="model" name="model">
        <option>Please choose car make first</option>
    </select>
{{ Form::close();}}

Then my route.php looks like this: 然后我的route.php看起来像这样:

Route::get('api/dropdown', function(){
    $input = Input::get('option');
    $maker = Client::find($input);
    $models = $maker->projects();
    return Response::eloquent($models->get(array('id','name')));
});

And finally, my script looks like this: 最后,我的脚本看起来像这样:

jQuery(document).ready(function($){
$('#make').change(function(){
        $.get("{{ url('api/dropdown')}}", 
            { option: $(this).val() }, 
            function(data) {
                var model = $('#model');
                model.empty();

                $.each(data, function(index, element) {
                    model.append("<option value='"+ element.id +"'>" + element.name + "</option>");
                });
            });
    });
});

I'm currently getting a javascript error in my console: 我目前在控制台中收到javascript错误:

Failed to load resource: the server responded with a status of 500 (Internal Server Error): http://localhost/test-project/api/dropdown?option=1
Failed to load resource: the server responded with a status of 500 (Internal Server Error): http://localhost/test-project/%7B%7B%20url('api/dropdown')%7D%7D?option=1

I believe I have CSRF tokens on, which apparently may affect things - but I'm really not sure how to work with them so just telling me to fix that wont help, I really need a slight bit of detail on exactly how to fix that (if you think that is the problem). 我相信我有CSRF令牌,这显然可能影响事情 - 但我真的不知道如何使用它们所以只是告诉我修复它不会有帮助,我真的需要一些细节如何解决这个问题(如果你认为这是问题)。

Alternatively, perhaps a modified or better solution would work better? 或者,也许改进的或更好的解决方案会更好? I'm sure there are many better ways to implement this type of solution. 我确信有更好的方法来实现这种类型的解决方案。

In summary, my question is: how can I fix my code above to work OR what is an alternate or better way to populate a dropdown list after an option is selected in another dropdown? 总之,我的问题是:我如何修复上面的代码才能工作,或者在另一个下拉列表中选择一个选项后,填充下拉列表的替代或更好的方法是什么?

I have poured through what feels like hundreds of solutions but none seem to work for me and my laravel-ness! 我已经倾注了数以百计的解决方案,但似乎没有一个对我和我的laravel-ness有用!

Edit: 编辑:

Complete route looks like this: 完整路线如下:

Route::resource('clients', 'ClientsController');

Route::resource('tasks', 'TasksController');

Route::controller('rates', 'RatesController');

Route::controller('projects', 'ProjectsController');

Route::controller('users', 'UserManagementController');

Route::controller('/', 'UsersController');

Route::get('api/dropdown', function(){
    $input = Input::get('option');
    $maker = Client::find($input);
    $models = $maker->projects();
    return Response::eloquent($models->get(array('id','name')));
});

The order in which routes are defined in Laravel is crucial. 在Laravel中定义路由的顺序至关重要。 Sometimes you'll be scratching your head and wondering why in the world you're getting an HttpNotFoundException. 有时你会挠头,想知道为什么在世界上你得到一个HttpNotFoundException。 Consider your routes.php file. 考虑你的routes.php文件。

When you define route like Route::controller('/', 'UsersController'); 当您定义Route::controller('/', 'UsersController');Route::controller('/', 'UsersController'); , in simple language its greedy route it will not allow routes defined below this route to execute, so when you define this type of route make sure its at the end ,用简单的语言,它的贪婪路线不允许在此路线下面定义的路线执行,因此当你定义这种类型的路线时,请确保它在最后

So make some change to your route like 所以对你的路线做一些改变

Route::get('api/dropdown', function(){
$input = Input::get('option');
$maker = Client::find($input);
$models = $maker->projects();
return Response::eloquent($models->get(array('id','name')));
});
Route::controller('/', 'UsersController');

That tutorial was written for Laravel 3 so somethings will be different. 那个教程是为Laravel 3编写的,所以有些东西会有所不同。 You can tell this because some of the methods are in snake_case rather than camelCase. 你可以这么说,因为有些方法是使用snake_case而不是camelCase。

return Response::json($models->select(array('id','name'))->get())

That should return a valid json response usable by Javascript. 这应该返回Javascript可用的有效json响应。 However, you may need to do some edits on your models as well if you followed that tutorial. 但是,如果您遵循该教程,您可能还需要对模型进行一些编辑。 belongs_to should be belongsTo and has_many should be hasMany . belongs_to应该是belongsTohas_many应该是hasMany

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM