我使用 "select2:opening" 事件和 Ajax 但 select2 选项没有填写第一次点击

I use "select2:opening" event with Ajax but select2 options do not fill in first click

我将“select2:opening”事件与 Ajax 一起使用,但 select2 选项不会在第一次点击时填写。但第二次单击 select2 下拉区域时它会起作用。这是我的代码:

$("#Select2ID").on("select2-opening", function () {
            var e = document.getElementById("AnotherID");
            code= e.options[e.selectedIndex].value;
            $.ajax(
                {
                    type: 'POST',
                    dataType: 'json',
                    url: '/Controller/Action',
                    data: { "Code": code},
                    success: function (data) {
                        selectClear("Select2ID");
                        var select = document.getElementById("Select2ID");

                        for (var item in data) {
                            var opt = document.createElement("option");
                            opt.value = data[item].id;
                            opt.innerHTML = data[item].text;
                            select.appendChild(opt);
                        } //for end.

                    }, //success end.
                    error: function (err) {
                        console.log(err);
                    },
                }); // ajax end.

            function selectClear(item) {
                var a = 0;
                var select = document.getElementById(item);
                while (select.firstChild) {
                    select.removeChild(select.firstChild);
                } //while end.

            }//selectTemizle end.

        });

我添加了 async:false 并解决了我的问题。

$.ajax(
    {
        async: false,    // <---
        type: 'POST',
        dataType: 'json',
        ...
...