【问题标题】:Nested Select2 with dependent AJAX call具有依赖 AJAX 调用的嵌套 Select2
【发布时间】:2014-10-16 13:02:39
【问题描述】:

我正在使用带有 jQ​​uery 的 Select2 来在表单上的 SELECT 元素之间建立依赖关系。我正在尝试建立典型的关系:国家有国家,国家有城市,城市有城镇等等。现在我正在这样做:

$(document).ready(function() {
    $(".pais").on('change', function() {
        pais = $(this).find('option:selected').val();
        $.get(Routing.generate('estados', {pais_id: pais})).success(function(data) {
            if (data.message === "") {
                $('.estado').empty().append('<option value="-1">Seleccione un estado</option>');
                $.each(data.entities, function(i, d) {
                    $('.estado').append('<option value="' + d.id + '">' + d.nombre + '</option>');
                });

                $('.estado').removeAttr('disabled');
                $('.estado').next('span').remove();
                $('.estado').closest('.form-group').removeClass('has-error');
                $('.estado').select2();
            } else {
                $('.estado').next('span').remove();
                $('.estado').closest('.form-group').addClass('has-error');
                $('.estado').after('<span class="help-block">' + data.message + '</span>');

                $('.estado').empty().append('<option value="-1">Seleccione un estado</option>').attr('disabled', 'disabled');
                $('.municipio').empty().append('<option value="-1">Seleccione un municipio</option>').attr('disabled', 'disabled');
                $('.ciudad').empty().append('<option value="-1">Seleccione un ciudad</option>').attr('disabled', 'disabled');
                $('.parroquia').empty().append('<option value="-1">Seleccione un parroquia</option>').attr('disabled', 'disabled');
            }
        }).error(function(data, status, headers, config) {
            if (status == '500') {
                message = "No hay conexión con el servidor";
            }
        });
    });

    $(".estado").change(function() {
        estado = $(this).find('option:selected').val();

        $.get(Routing.generate('municipios', {estado_id: estado})).success(function(data) {
            ...
        }).error(function(data, status, headers, config) {
            ...
        });

        $.get(Routing.generate('ciudades', {estado_id: estado})).success(function(data) {
            ...
        }).error(function(data, status, headers, config) {
            ...
        });
    });

    $(".municipio").change(function() {
        municipio = $(this).find('option:selected').val();

        $.get(Routing.generate('parroquias', {municipio_id: estado})).success(function(data) {
            ...
        }).error(function(data, status, headers, config) {
            ...
        });
    });
});

但是当我两次或更多次更改相同的 SELECT "Estado" 或 "Ciudad" 或 "Municipio" 或 "Parroquia" 时,我收到此错误:

未捕获的异常:未为 Select2 s2id_municipio 定义查询函数

注意:我多次更改“Estado”以获得此错误,以防您可以尝试重现相同的错误

也许错误在我的逻辑中,也可能不在我的逻辑中,所以我需要一些帮助,我的问题是:可以使用 AJAX 调用构建嵌套的依赖 SELECT(当然应用 Select2)以构建相同的结构?

您可以查看link 中的示例,选择任何选项,例如“Persona Natural”,然后在“Pais de Residencia”的“Datos Personales”中选择“Venezuela”,然后尝试更改“Estado” " 两次或更多次,看看会发生什么,对此有何建议?

PS:对于某些部分的西班牙语感到抱歉,这是一个西班牙客户的工作,他讨厌英语(不要问我为什么)

【问题讨论】:

标签: javascript jquery jquery-select2


【解决方案1】:

您应该真正使用 Select2 的 AJAX 功能,而不是自己做。这意味着将基础元素从 &lt;select&gt; 更改为 &lt;input type="hidden" /&gt; 并将 Select2 指向您的数据源。

https://ivaynberg.github.io/select2/#ajax

这是一个如何转换下拉状态的示例。

var $pais = $("select.pais");
var $estados = $("input.estados");

$estados.select2({
    placeholder: "Seleccione un estado",
    ajax: {
        url: function () {
            var pais = $pais.val();
            return Routing.generate('estados', {pais_id: pais});
        },
        results: function (data) {
            return {
                results: data.entities
            };
        }
    },
    formatNoResults: function () {
        return "No se encontraron estados para el país actual";
    }
    formatAjaxError: function () {
        return "No hay conexión con el servidor";
    }
}).select2("enable", false);

请注意,我使用$("input.estados") 作为选择器,而不仅仅是类。这是因为 Select2 会将类复制到 Select2 容器中,并且当您获得多个元素时再次引用它时会导致问题。这个解释多一点in this answer

【讨论】:

    【解决方案2】:

    gist 是一个易于使用的 JS 类,用于使 Select2 列表框依赖。例如 -

    new Select2Cascade($('#parent'), $('#child'), '/api/to/load/:parentId:/childs');
    

    codepen 上查看演示。这里还有一个关于how to use 的帖子。

    【讨论】:

    • 我收到了这个错误兄弟 TypeError: b.dataAdapter is null
    • @SomwangSouksavatd,感谢您的提问,但很难根据这个小描述发表评论。你能分享更多细节吗? JSFiddle 的 Codepen 上的示例可能会有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-24
    • 2011-03-19
    • 2020-06-24
    • 2014-11-26
    • 2015-02-16
    • 1970-01-01
    • 2014-04-09
    相关资源
    最近更新 更多