私は既にthis、this、thisと書類the most important hereに従って読んでいますが、それらのどれも私のために働いていません。 AJAX select2を使用しようとしています。私は一般的な "選択"項目を作ろうとしています。select2 4.0 AJAXプリフィットハウツー?
data-select2-json
属性を持つすべての要素については、値のajax URLを付けてselect2
を適用します。
$('[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に非常に近いです。私は、HTML内の値を追加するかしたい:私の問題は、AJAXのinitiatilizeある
<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({..
)で初期化しますが、このdoesntの仕事と私に空白の値を与える:
NB:the solution here given by Kevin Brown NB:the solution here given by Kevin Brownは全く同じ結果をもたらします。
他の解決策は、「&init=1
」(またはそのような何か)ので、それぞれの値についてchecked: true
のような追加のパラメータで結果を送信するサーバーなどのパラメータでURLにAJAXに依頼することです、と私はそれらと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;
}
私の答えはあなたのために働いていませんでしたか?フィードバックをお願いします。 –