带相关AJAX调用的嵌套Select2 [英] Nested Select2 with dependent AJAX call

查看:129
本文介绍了带相关AJAX调用的嵌套Select2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Select2与jQuery一起使用,以在表单上的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)以构建相同的结构吗?

您可以在此链接中查看示例. >选择任何选项,例如"Persona Natural",然后在"Pais de Residencia"的"Datos Personales"处选择委内瑞拉",然后尝试两次或多次更改"Estado"字段,看看发生了什么,对此有任何建议?

PS:很抱歉,在某些地方使用西班牙语,这对西班牙客户来说是一项工作,他讨厌英语(不要问我为什么)

解决方案

您应该真正使用Select2的AJAX功能,而不要自己做.这意味着将基础元素从<select>更改为<input type="hidden" />,并将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容器,并且当您获得多个元素时再次引用它会导致问题. 在此答案中进行了解释.

I'm using Select2 with jQuery to build a dependent relationship between SELECT elements on a form. I'm trying to build the typically relation: Country has States, States has Cities, City has Town and so on. Right now I'm doing in this way:

$(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) {
            ...
        });
    });
});

But when I change the same SELECT "Estado" or "Ciudad" or "Municipio" or "Parroquia" twice or more times I got this error:

uncaught exception: query function not defined for Select2 s2id_municipio

Note: I changed "Estado" more than one time to get this error in case you can try to reproduce the same error

Maybe the error is in my logic or maybe not so I need some help here and my question is: it's possible to build nested dependent SELECT (applying Select2 of course) with AJAX calls for build the same structure?

You can take a look to live example in this link choose any option for example "Persona Natural" and then at "Datos Personales" at "Pais de Residencia" choose "Venezuela" and then try to change the "Estado" field two or more times and see what's happen, any advice on this?

PS: Sorry for Spanish language on some parts this is a job for a Spanish client and he hates English (don't ask me why)

解决方案

You should really be using Select2's AJAX functionality instead of doing it on your own. This means changing the underlying elements from <select> to <input type="hidden" /> and pointing Select2 at your data source.

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

Here is an example of how to convert the states drop down.

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);

Note that I am using $("input.estados") for the selector instead of just the class. This is because Select2 will copy the class to the Select2 container, and that will cause problems when referencing it again as you get multiple elements. This is explained a little more in this answer.

这篇关于带相关AJAX调用的嵌套Select2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆