3

名前の動的リストを表示するために 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>";
    },
});
4

2 に答える 2

2

コードの助けを借りて修正しました。これが私のdone()部分です:

done(function(resp) {
  d = $(s2).select2("data"); // s2 is this select2 object. in your case $('.' + id + '-select2', nextFrame);
  $(s2).select2("close"); // first close the opened list. select2 doesn't close "result not found".
  d.push({id: resp.id, title: resp.title}); // now add ajax response to our current select2 data. in my case response contains count, id and title of the added/suggested
  $(s2).select2("data", d);
});
于 2014-07-16T12:53:55.543 に答える