select2 过滤本地 JSON 数据结果与查询词

select2 filter local JSON data results with query term

我正在实施 select2 版本 3.5.0。我在文档就绪函数中使用以下 jQuery:

jQuery.getJSON('/rest/call/to/retrieve/JSON').done(
  function( data ) {
     jQuery('#byProductName').select2({
         placeholder: 'Type any portion of a single product name...',
         allowClear: true,
         minimumInputLength: 0,
         multiple: true,
         id: function(data){ return data.product; },
         data: data,
         formatResult: function(data){ return data.product; },
         formatSelection: function(data){ return data.product; },
     });
  }
);

HTML 隐藏输入元素:

<div id='freeForm'>
    <input name='Search Products' type='hidden' id='byProductName'>
</div>

JSON 结果:

[{"product":""},{"product":" windows"},{"product":" mac"},
 {"product":" linux"},{"product":" RHEL"},{"product":"Test product list"}]

下拉菜单正确填充了我的值,我可以 select 多个项目并成功删除它们。但是,当我在输入字段中键入一个字符串来过滤结果集时,它并没有过滤。

我试过将数据更改为:

data: function (data, term){
    return { 
        results: data,
        query: term }
    },

但是单击下拉列表后出现此错误:

Uncaught TypeError: Cannot read property 'length' of undefined - select2 line 1784

如何使用查询词成功过滤结果列表?

来自 Select2 documentationdata 选项:

Options [sic] for the built in query function that works with arrays.

If this element contains an array, each element in the array must contain id and text keys.

Alternatively, this element can be specified as an object in which results key must contain the data as an array and a text key can either be the name of the key in data items that contains text or a function that retrieves the text given a data element from the array.

这意味着您有两个选择:

(1) 将您的 data 数组更改为具有 idtext 属性的对象数组,然后再将其提供给 .select2()。然后,您可以去掉 idformatResultformatSelection 选项。

jQuery.getJSON('/rest/call/to/retrieve/JSON').done(
    function( data ) {

        data = $.map(data, function(item) {
            return { id: item.product, text: item.product }; 
        });

        jQuery('#byProductName').select2({
            placeholder: 'Type any portion of a single product name...',
            allowClear: true,
            minimumInputLength: 0,
            multiple: true,
            data: data
        });
    }
);

jsfiddle

(2) 为 data 选项提供具有 resultstext 属性的对象。在这种情况下,您仍然需要提供 id 选项,但您可以去掉 formatResultformatSelection 选项。

jQuery.getJSON('/rest/call/to/retrieve/JSON').done(
    function( data ) {
        jQuery('#byProductName').select2({
            placeholder: 'Type any portion of a single product name...',
            allowClear: true,
            minimumInputLength: 0,
            multiple: true,
            data: { results: data, text: 'product' },
            id: function(item) { return item.product; }
        });
    }
);

jsfiddle