【发布时间】:2016-03-28 02:50:27
【问题描述】:
我已经阅读了this、this、this 和文档the most important here,但它们都不适合我。 我正在尝试使用 AJAX select2。我正在尝试制作一个通用的“选择”项。
因此,对于所有具有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}
它非常接近您can find in the documentation 的 AJAX 示例。我的问题是 AJAX 初始化:我想在 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>
然后用 select2 初始化(= 上面的代码 $(this).select2({.. )但这不起作用并给我空白值:
注意:the solution here given by Kevin Brown 也不起作用,给我的结果完全相同。
另一种解决方案是在 AJAX 中使用诸如“&init=1”(或类似的东西)之类的参数向 URL 询问,以便服务器将发送结果并为每个值添加诸如 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;
}
【问题讨论】:
-
我的回答对您不起作用吗?请提供反馈。
标签: javascript jquery json ajax select2