使用 select2、json 请求和 Laravel 的动态下拉列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30273155/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:34:09  来源:igfitidea点击:

Dynamic dropdowns using select2, json request and Laravel

javascriptphplaravellaravel-5jquery-select2

提问by Matthew Malone

I am trying to get dynamic drop downs working with Laravel and Select2. There are two drop downs; one for companies i.e. "company2" and one for locations that belong to that company i.e. "location2".

我正在尝试使用 Laravel 和 Select2 进行动态下拉。有两个下拉菜单;一个用于公司,即“company2”,另一个用于属于该公司的位置,即“location2”。

For the life of me, I cannot figure out how to make the "company2" drop down fire a event to read that companies locations, if it is changed! What am I doing wrong in the javascript section of this code! (everything else works)

对于我的生活,我无法弄清楚如何让“company2”下拉菜单触发一个事件来读取该公司的位置,如果它被改变了!我在这段代码的 javascript 部分做错了什么!(其他一切正常)

Route

路线

Route::controller('api', 'ApiController');

Controller (ApiController)

控制器(ApiController)

public function getLocations($companyId)
{
    return Location::where('company_id', $companyId)->lists('id', 'name');
}

Example output from address "api/locations/7"

地址“api/locations/7”的示例输出

{"Yellowstone":"8"}

View (form open/close section omitted)

查看(表单打开/关闭部分省略)

{!! Form::select('company_id', $companies, null, ['class' => 'company2 form-control']) !!}
{!! Form::select('location_id', $locations, null, ['class' => 'location2 form-control']) !!}

View (Javascript)

查看(Javascript)

<script type="text/javascript">
    $(document).ready(function() {
        $(".company2").select2();
        $(".location2").select2();
    });

$(".company2").select2().on('change', function() {
    var $company2 = $('.company2');
    $.ajax({
        url:"../api/locations/" + $company2.val(),
        type:'GET',
        success:function(data) {
            var $location2 = $(".location2");
            $location2.empty();
            $.each(data, function(value, key) {
                $location2.append($("<option></option>").attr("value", value).text(key));
            }); 
            $location2.select2();
        }
    });
}).trigger('change');
</script>

The view is passed a list of active companies when initialized i.e.

视图在初始化时传递一个活动公司的列表,即

$companies = Company::lists('trading_name', 'id');

采纳答案by haakym

Replace your javascript with the following, you may need to tweak some of it. Please make sure you look through the comments.

将您的 javascript 替换为以下内容,您可能需要对其进行一些调整。请务必仔细阅读评论。

var $company2 = $('.company2');
var $location2 = $(".location2");

$company2.select2().on('change', function() {
    $.ajax({
        url:"../api/locations/" + $company2.val(), // if you say $(this) here it will refer to the ajax call not $('.company2')
        type:'GET',
        success:function(data) {
            $location2.empty();
            $.each(data, function(value, key) {
                $location2.append($("<option></option>").attr("value", value).text(key)); // name refers to the objects value when you do you ->lists('name', 'id') in laravel
            });
            $location2.select2(); //reload the list and select the first option
        }
    });
}).trigger('change');

Change the following when you grab the location data from the controller

从控制器获取位置数据时更改以下内容

public function getLocations($companyId)
{
    return Location::where('company_id', $companyId)->lists('name', 'id');
}

回答by Bruno Ribeiro

you can try this :

你可以试试这个:

$.getJSON("getOptions.php", function (json) {
      $("#inputs").select2({
         data: json,
         width: "180px"
      });
 });

example json output :

示例 json 输出:

    {id:0,text:"Text 1"},
    {id:1,text:"Text 2"},
    {id:2,text:"Text 3"},
    {id:3,text:"Text 4"},
    {id:4,text:"Text 5"}