select2 4.0 ajax模式下的初始值

Edd*_*die 4 javascript ajax jquery jquery-select2 jquery-select2-4

我的页面上有以下选择:

<select><option value="1" selected="selected">Caption</option></select>
Run Code Online (Sandbox Code Playgroud)

我调用 select2 (v 4.0) init:

city.select2({
    ajax: {
        url: <...>,
        data: <...>,
        processResults: <...>,
        cache: true
    },
    escapeMarkup: function(markup){ return markup; },
    minimumInputLength: 0,
    templateResult: function(repo){ return repo.name; },
    templateSelection: function(repo){ return repo.name; }
});
Run Code Online (Sandbox Code Playgroud)

问题是 select2 正在重置默认选定值并显示空白字符串。有没有办法在 select2 init 上设置默认值?

Kev*_*own 5

问题出在您的templateSelection方法中,因为您期望name数据对象上有一个属性。除了现在需要的事实之外text,如果重新映射它,您将不需要该方法,您不处理数据对象具有属性的情况text

city.select2({
    ajax: {
        url: <...>,
        data: <...>,
        processResults: <...>,
        cache: true
    },
    escapeMarkup: function(markup){ return markup; },
    minimumInputLength: 0,
    templateResult: function(repo){ return repo.name || repo.text; },
    templateSelection: function(repo){ return repo.name || repo.text; }
});
Run Code Online (Sandbox Code Playgroud)

这应该可以解决您的问题并正确显示初始选择。