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

Tom*_*mmy 10 ajax jquery jquery-select2

我正在使用带有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
    });
Run Code Online (Sandbox Code Playgroud)

好吧,如果找不到客户端,用户可以使用按钮打开模态并添加新客户端,可以使用新客户端的返回(带有id和namae的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;
    });
Run Code Online (Sandbox Code Playgroud)

ale*_*exw 21

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

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

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

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


Tom*_*Tom 1

我设法让它发挥作用。在 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});
Run Code Online (Sandbox Code Playgroud)