如何将数据传递给 select2 version > 4.0

How to pass data to select2 version > 4.0

我是第一次尝试使用 select2

我想从静态数组中获取数据。你能帮帮我吗?

这是我的代码:

$(document).ready(function() {

    var names = [{"id":"1","name":"Adair,James"}
             , {"id":"2","name":"Anderson,Peter"}
             , {"id":"3","name":"Armstrong,Ryan"}];

    $("#e10_2").select2({
        processResults: function(){
          return {
            results: $.map(names, function(obj) {
              return { id: obj.id, text: obj.name };
            })
          };
        }
    });

});

您可以使用 data 选项将数组传递给 select2 作为 :

$("#e10_2").select2({ data: names });

如果您没有 text 属性调整数组,请检查为此目的制作的文档部分 The id and text properties are strictly enforced,例如:

$(function () {
    var names = [{"id":"1","name":"Adair James"}
                 , {"id":"2","name":"Anderson Peter"}
                 , {"id":"3","name":"Armstrong Ryan"}];

    var data = $.map(names, function (obj) {
      obj.id = obj.id;
      obj.text = obj.name;

      return obj;
    });

    $("select").select2({width: '100%',data: data});
});

希望对您有所帮助。

$(function () {
  var names = [{"id":"1","name":"Adair James"}
               , {"id":"2","name":"Anderson Peter"}
               , {"id":"3","name":"Armstrong Ryan"}];

  var data = $.map(names, function (obj) {
    obj.id = obj.id;
    obj.text = obj.name;

    return obj;
  });

  $("select").select2({width: '100%',data: data});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://select2.github.io/dist/js/select2.full.js"></script>
<link href="https://select2.github.io/dist/css/select2.min.css" rel="stylesheet"/>
<select></select>