jQuery 使用 AJAX 插入后在 Select2 中设置数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14311657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:26:42  来源:igfitidea点击:

Set data in Select2 after insert with AJAX

jqueryajaxjquery-select2

提问by Tommy

i'm using the Select2 with AJAX (the code below):

我正在使用带有 AJAX 的 Select2(下面的代码):

$(".select2-ajax").select2({
        placeholder: "Search user",
        minimumInputLength: 1,
        ajax: {
            url: $('#url-search-client').val(),
            dataType: 'json',
            type: 'post',
            data: function (term, page) {
            return {
                filter: term
            };
            },
            results: function (data, page) {
            return {results: data};
            }
        },
        width : '50%',
        formatInputTooShort: function () {return 'Informe mais caracteres'; },
        formatResult: formatResultSelectAjax, // omitted for brevity, see the source of this page
        formatSelection: formatSelectAjaxValue, // omitted for brevity, see the source of this page
        dropdownCssClass: "bigdrop" // apply css that makes the dropdown taller
    });

Well, if not found client, the user can be use a button to open a modal and add the new client, is possible use the return(json with id and namae) of new client and put the data (like name) into the select2 as selected?

好吧,如果没有找到客户端,用户可以使用按钮打开一个模式并添加新客户端,可以使用新客户端的返回(带有id和namee的json)并将数据(如名称)放入select2作为选择?

$('.btn-form-client').click(function() {
        $.ajax({
            url: $('#frm-client').attr('action'),
            dataType: 'json',
            type: 'post',
            data: $('#frm-client').serialize()
        }).done(function (data) {
            $('#modal-client').modal('hide')
        });
        return false;
    });

回答by alexw

Starting in v4.x, select2 no longer uses the hidden inputfield. Instead, you create a new Optionand append it to your selectelement:

从 v4.x 开始,select2 不再使用隐藏input字段。相反,您创建一个新的Option并将其附加到您的select元素:

var newOption = new Option(data.name, data.id, true, true);
$(".select2-ajax").append(newOption).trigger('change');

The combination of the truearguments and trigger('change')will make sure your new <option>is automatically selected after being added.

true参数的组合和trigger('change')将确保您的新<option>添加后自动选择。

See my codepenfor a complete working example.

有关完整的工作示例,请参阅我的codepen

回答by Tom

I managed to make it work. After POST in jQuery, i get a JSON with the new data and set the hidden input and the select ('.select2-ajax')

我设法让它工作。在 jQuery 中 POST 后,我得到一个包含新数据的 JSON 并设置隐藏输入和选择('.select2-ajax')

$('#client=id').val(data.id);
$('#modal-solicitante').modal('hide'); //This is my
$(".select2-ajax").select2('data', {id: data.id, name: data.name, email: data.email});