【问题标题】:I use "select2:opening" event with Ajax but select2 options do not fill in first click我在 Ajax 中使用“select2:opening”事件,但 select2 选项未填写第一次单击
【发布时间】:2020-12-30 08:13:41
【问题描述】:

我在 Ajax 中使用“select2:opening”事件,但 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.

        });

【问题讨论】:

标签: javascript jquery ajax promise jquery-select2


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2021-12-28
    • 1970-01-01
    • 2013-12-24
    • 2017-06-25
    • 2016-02-03
    • 2021-04-19
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多