Select2 AJAX 以编程方式更改时不更新

Select2 AJAX doesn't update when changed programatically

我有一个远程获取数据的 Select2,但我也想以编程方式设置它的值。当尝试以编程方式更改它时,它会更新 select 的值,并且 Select2 会注意到更改,但不会更新其标签。

https://jsfiddle.net/Glutnix/ut6xLnuq/

$('#set-email-manually').click(function(e) {

    e.preventDefault();

    // THIS DOESN'T WORK PROPERLY!?

    $('#user-email-address') // Select2 select box
        .empty()
        .append('<option selected value="test@test.com">test@test.com</option>');
    $('#user-email-address').trigger('change');

});

我已经尝试了很多不同的东西,但我做不到。我怀疑这可能是一个错误,所以在项目上 filed an issue

对我来说,没有 AJAX 是这样的:

var select = $('.user-email-address');
var option = $('<option></option>').
     attr('selected', true).
     text(event.target.value).
     val(event.target.id);
/* insert the option (which is already 'selected'!) into the select */
option.appendTo(select);
/* Let select2 do whatever it likes with this */
select.trigger('change');

阅读文档我认为你可能以错误的方式设置了选项,你可以使用

data: {}

而不是

data, {}

并设置 {} 中包含的选项,用“,”分隔,如下所示:

{
  option1: value1,
  option2: value2
}

所以我已经更改了这部分代码:

$('#user-email-address').select2('data', {
  id: 'test@test.com',
  label: 'test@test.com'
});

至:

$('#user-email-address').select2({'data': {
    id: 'test@test.com',
    label: 'test@test.com'
  }
});

标签正在更新。

updated fiddle

希望对您有所帮助。

编辑:

我更正自己,您似乎可以按照处理数据的方式传递数据,{}

数据模板有问题..

再次阅读文档,数据模板似乎应该是 {id, text} 而你的 ajax 结果是 {id, email},设置手册部分不起作用,因为它试图 return 来自 {id, text} 对象的电子邮件,没有电子邮件。因此您要么需要将格式选择功能也更改为 return 文本而不是仅电子邮件,要么重新映射 ajax 结果。

我更喜欢重新映射 ajax 结果并采用标准方式,因为这将使您的占位符也能正常工作,但目前无法正常工作,因为占位符模板似乎也是 {id,text} 。

所以我已经更改了这部分代码:

        processResults: function(data, params) {
            var payload = {
                results: $.map(data, function(item) {
                  return { id: item.email, text: item.email }; 
                })
            };
            return payload;
        }

并删除了这些,因为它们不再需要了:

    templateResult: function(result) {
        return result.email;
    },
    templateSelection: function(selection) {
        return selection.email;
    }

已更新 fiddle:updated fiddle

Kevin-Brown on GitHub replied 并表示:

The issue is that your templating methods are not falling back to text if email is not specified. The data objects being passed in should have the text of the <option> tag in the text property.

事实证明,这两种方法的结果参数中的数据比 AJAX 响应更多!

templateResult: function(result) {
    console.log('templateResult', result);
    return result.email || result.text;
},
templateSelection: function(selection) {
    console.log('templateSelection', selection);
    return selection.email || selection.id;
},

这是功能齐全的 updated fiddle