名前の動的リストを表示するために select2 を使用しています。名前は、ユーザーがタイプすると類似してサーバーから取得されますが、名前が見つからない場合は、名前をデータベースに追加する「提案」リンクを表示します。
「提案」リンクは、選択の通知領域に表示されます (サーバーにクエリを実行すると、「検索中...」が表示されます)。ユーザーが「提案」を押すと、前述のように、提案された名前をデータベースに追加する要求が行われます。さて、そのリクエストが応答したら、その名前をselect2のリストに追加して選択し、ドロップボックスを閉じます。
私はこの努力で何も成功していません =) 「val」を使用してみましたが、正しく実行していないか、それが正しい方法ではありません。これは私が今持っているものからのコードの抜粋です:
$('.' + id + '-select2', nextFrame).select2({
ajax: {
url: url,
dataType: 'json',
results: function(data) {
var results = [], it;
for (it in data) {
results.push({
id: data[it]['pid'],
text: data[it]['name']
});
}
return { results: results }
},
data: function(text) {
return { name: text }
}
},
formatNoMatches: function(text) {
// Add the AJAX behavior to the anchor, but do it asynchronously
// This way we give time to select2 to render the layout before we configure it
setTimeout(function() {
$('#' + id + '-ajax-anchor').on('click', function(e) {
var target = $(e.target);
$.ajax({
url: target.attr('href'),
type: 'POST',
dataType: 'json',
data: {
name: text
},
})
.done(function(response) {
/*
Need help here !!
1) Add the response to the list
2) Select it
3) Close
*/
})
;
e.preventDefault();
});
}, 1);
return "No match, <a id='" + id + "-ajax-anchor' href='" + url + "'>suggest</a>";
},
});