javascript - 使用ajax时如何动态添加元素到select2

标签 javascript jquery jquery-select2

我正在使用 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>";
    },
});

最佳答案

刚刚在您的代码帮助下修复了它。这是我的 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);
});

关于javascript - 使用ajax时如何动态添加元素到select2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18200115/

相关文章:

jquery - 单击时更改 select2 选项

python - 更新 Django-Select2 AutoModelSelect2Field 的查询集

javascript - 在不发送 HTTP 请求的情况下使用 documentFragment 解析 HTML

javascript - jQuery DataTables 中的空表体

javascript - 如何修复 JS 不适应新的 HTML 输入

javascript - 从 FunctionComponent 返回的子级中断父级渲染逻辑

javascript - 如何管理网站中的 jQuery 库?

javascript - 在计算输入类型数字的金额时出现问题

c# - 将文件数组从 Jquery ajax 发送到 Controller 操作

javascript - 如何将带有ajax的select2添加到jquery查询生成器?