我已阅读this,this,this并根据文档the most important here,但他们都没有为我工作。 我正在尝试使用AJAX select2。我试图做一个通用的“选择”项目。select2 4.0 AJAX预填充howto?
因此,对于所有具有data-select2-json
属性的元素,我应用select2
以及data-select2-json
值中的ajax URL。
$('[data-select2-json!=""][data-select2-json]').each(function() {
var url = $(this).attr('data-select2-json');
var pg_size = $(this).attr('data-select2-page-size') | 30;
$(this).select2({
language: language_code,
tokenSeparators: [',', ' '],
ajax: {
url: url,
dataType: 'json',
delay: 300,
data: function (params) {
return {
q: params.term, // -> q=[search term]
page: params.page // -> page=[no page]
};
},
processResults: function (data, params) {
params.page = params.page || 1;
console.log(data.items);
return {
results: data.items,
pagination: {
more: (params.page * pg_size) < data.total
}
};
},
cache: true
},
// let our custom formatter work
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 1,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
});
它运作良好!
JSON服务器发送总是格式如下:
{"items":
[{"item": "Fran\u00e7ais", "id": 1},
{"item": "Finlandais", "id": 5},
{"item": "Chinois simplifi\u00e9", "id": 15}
],
"total": 3}
这是非常接近的AJAX样品你can find in the documentation。我的问题是AJAX initiatilize:我想要么增加值在HTML:
<select multiple="multiple" class="form-control"
data-select2-json="/fr/chez-moi/tags/langues"
multiple="multiple"
name="known_languages">
<option value="1" selected="selected">Français</option>
<option value="2" selected="selected">Chinois simplifié</option>
</select>
,然后用选择2初始化(=上面的代码$(this).select2({..
),但是这并不工作,并给了我空白值:
注意:the solution here given by Kevin Brown也不起作用,并给我完全相同的结果。
另一种方案是在AJAX问到URL中包含“&init=1
”(或类似的东西),所以服务器将发送结果与添加参数,如checked: true
每个值的参数,我会叫select2
与值。
关于如何预先填写select2
的文档中没有明确说明。我应该怎么做?
这里是我的其他功能:
function item_or_text(obj) {
if (typeof(obj.item)!='undefined') {
return (obj.item.length ? obj.item : obj.text);
}
return obj.text;
}
function formatRepo(data) {
if (data.loading) return data.text;
var markup = item_or_text(data);
console.log('formatRepo', data, markup);
return markup;
}
function formatRepoSelection(item) {
var retour = item_or_text(item);
console.log('formatRepoSelection', item, item.item, retour);
return retour;
}
我的答案不适合你吗?请提供反馈。 –