我正在使用select2插件(ivaynberg.github.io/select2) .

我正在尝试显示下拉列表(选择) .

通过ajax获取数据,为此我创建了2个servlet .

  • 下拉菜单网址:'/testPr1/servlet1'

返回:
[{"id":1,"text":"Genre1"},{"id":2,"text":"Genre2"},{"id":3,"text":"Genre3"},{"id":4,"text":"Genre4"}]

  • 初始化数据网址:'/testPr1/servlet2'

返回:
[{"id":1,"text":"Genre1"},{"id":2,"text":"Genre2"}]

我为select2创建隐藏元素(并设置初始值)

从列表中选择电影类型:

<input type="hidden" id="film_genre_cbox" style="width:600px" value="1,2" />

然后我开始创建下拉列表

var select_config2 = {
            minimumInputLength: 0,
            allowClear: true,
            placeholder: "Select film genre",
            tags: true,
            ajax: {
              url: '/testPr1/servlet1',
              dataType: 'json',
              type: "GET",
              quietMillis: 0,
              data: function (term) {
                return {
                  term: term
                };
              },
              initSelection: function (element, callback) {
              },
              results: function (data) {
                return {
                  results: $.map(data, function (item) {
                    return {
                      text: item.text,
                      id: item.id
                    }
                  })
                };
              }
            }
          };

    $("#film_genre_cbox").select2(select_config2);

效果很好,选择将Genre1和Genre2排除为初始值

但我希望将这两种类型视为输入中的选定元素,如下所示:

picture1

然后我尝试通过ajax初始化select2

var select_config1 = {
    minimumInputLength: 0,
    allowClear: true,
    placeholder: "Select film genre",
    tags: true,
    ajax: {
      url: '/testPr1/servlet1',
      dataType: 'json',
      type: "GET",
      quietMillis: 0,
      data: function (term) {
        return {
          term: term
        };
      }
    },
   initSelection: function (element, callback) {
          var id = $(element).val();
//        alert(id.toString());
          if (id !== "") {
              $.ajax({
                  url:'/testPr1/servlet2',
                  dataType: "json",
                  type: "GET",
                  quietMillis: 0,
              }).done(function(data) {
                  alert(data.toString());
                return callback(data);
              });
          } else {
              callback([]);
        }
      },
      results: function (data) {
        return {
          results: $.map(data, function (item) {
            return {
              text: item.text,
              id: item.id
            }
          })
        };
      }
  };
$("#film_genre_cbox").select2(select_config1);

结果我得到init的选择

picture2

但是当我开始下拉时,我没有菜单(Genre3,Genre4)

and error “Uncaught TypeError: options.results is not a function”.

我使用的Libs

jquery-2.1.4.js
/select2_v3.5/select2.js
select2_v3.5/select2.css

哪里出错了?