繁体   English   中英

Select2 具有预选值的远程数据

[英]Select2 remote data with pre selected value

我想加载 select2 远程数据以及一些选定的值。

我的代码是这样的

$("#category_input").select2({
    dropdownParent: $("#changeCategoryModal"),
    placeholder: "Change Category",
    closeOnSelect: false,
    maximumSelectionLength: 3,
    ajax: {
        url: url,
        dataType: 'json',
        processResults: function(response) {
            return {
                results: response,
            };
        }
    }
});

如果我想选择 id 1,2,3(示例),我可以在这里做什么?

(我在 Laravel 刀片模板中使用此脚本)

如果我理解您的查询正确,您可以尝试以下方法。

方法:

  • 我们在fetch_data function 中跟踪 AJAX 请求
  • 在 function 中处理我们的数据并从刀片渲染该数据
  • 最后返回对 AJAX 请求的响应

controller.php

public function fetch_data()
{
    if(request()->ajax()) {

        //process your data and logics

        //here is some sample data to understand the flow
        $selected_options = array(1, 3);

        $data = array(['id' => 1, 'name' => 'produc1'], ['id' => 2, 'name' => 'produc2'], ['id' => 3, 'name' => 'produc3']);
        
       return view('select2', compact('selected_options', 'data'))->render();
    }
}

select2.blade.php

@foreach($data as $key => $val)

    <option value="{{$val['id']}}" @if(in_array($val['id'], $selected_options)) selected @endif> $val['name'] </option>

@endforeach

暂无
暂无

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

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