根据先前的选择,使用ajax更改选择选项

时间:2020-03-10 16:26:13

标签: jquery ajax select dropdown onchange

我正在尝试根据先前的选择内容来更新三个链接的国家->省->城市选择框。我的javascript的第二部分不起作用

$(document).ready(function() {


            var $country = $('#person_country');
            var $province = $('#person_province');

            $country.change(function () {
                // ... retrieve the corresponding form.
                var $form = $(this).closest('form');
                var data = {};
                data[$country.attr('name')] = $country.val();
                // Submit data via AJAX to the form's action path.
                $.ajax({
                    url: $form.attr('action'),
                    type: $form.attr('method'),
                    data: data,
                    success: function (html) {
                        // Replace current field ...
                        $('#person_province').replaceWith(
                            // ... with the returned one from the AJAX response.
                            $(html).find('#person_province')
                        );
                    }
                });
            });


            $province.change(function () {
                // ... retrieve the corresponding form.
                var $form = $(this).closest('form');
                // Simulate form data, but only include the selected value.
                var data = {};
                data[$province.attr('name')] = $province.val();
                // Submit data via AJAX to the form's action path.
                $.ajax({
                    url: $form.attr('action'),
                    type: $form.attr('method'),
                    data: data,
                    success: function (html) {
                        $('#person_city').replaceWith(
                            // ... with the returned one from the AJAX response.
                            $(html).find('#person_city')
                        );
                    }
                });
            });
        });

第二个更改功能不起作用。 我究竟做错了什么? 有没有办法调用两次change和ajax函数?

1 个答案:

答案 0 :(得分:2)

第二个更改功能不起作用。

在这种情况下,您要将事件添加到在渲染过程中创建的第二个select#person_province),但是,当您更改第一个select时,有以下代码: / p>

$('#person_province').replaceWith(
    $(html).find('#person_province')
);

这将删除现有的select和分配给该select的所有现有事件。

一种选择是使用事件委托:

$(document).on("change", "#person_province", function...

另一种选择是不使用.replaceWith,而是用新内容替换内容(或内部HTML),这将使select和分配的事件保持不变。< / p>

在第一个select回调中,将.replaceWith更改为:

$('#person_province').html(
    $(html).find("#person_province").html())
);
相关问题