【问题标题】:Getting select2 to refresh data using ajax on dropdown让select2在下拉菜单上使用ajax刷新数据
【发布时间】:2016-11-28 16:30:51
【问题描述】:

我有以下 JavaScript 使用 select2 https://select2.github.io/ 填充下拉列表

它工作正常,并在第一次加载页面时填充列表。 从那时起,即使添加了数据,它也不会刷新列表,因为它只调用一次 AJAX。即使我重新加载页面,下拉列表也不会刷新,也不会触发 AJAX 调用(除非我关闭并重新打开浏览器,然后才会触发 AJAX 调用)

有没有办法在每次打开下拉菜单时进行 ajax 调用。我尝试了 .on("select2-open") 选项,但没有任何运气。

抱歉,我对 JavaScript 了解不多。

$("#Location").select2({
            placeholder: "Select a known location", // Placeholder text
            allowClear: true, //Allows deselection of chosen address
            ajax: {
                url: '/AlertInterface/NewAlertLocations', // Where we want the ajax to call
                dataType: 'json', // The datatype we are expecting to be returned
                type: "GET", //Just a get method
                //Data: allows us to pass a parameter to the controller
                data: function (query) {
                    console.log(query)
                    return { search: query.term }
                },
                //processes the results from the JSON method and gives us the select list
                processResults: function (data) {
                    console.log(data)
                    return {
                        results: JSON.parse(data)
                    };
                }
            }
        });

编辑:

我确实尝试过使用

$("#Location").on("select2:open", function () { $("#Location").select2(); })

但这并没有帮助。 :-(

【问题讨论】:

    标签: asp.net-mvc-5 asp.net-ajax jquery-select2


    【解决方案1】:

    您的代码中有语法错误。 请检查以下代码,

    $("#Location").select2({
                placeholder: "Select a known location", // Placeholder text
                allowClear: true, //Allows deselection of chosen address
                ajax: {
                    url: '/AlertInterface/NewAlertLocations', // Where we want the ajax to call
                    dataType: 'json', // The datatype we are expecting to be returned
                    type: "GET", //Just a get method
                    //Data: allows us to pass a parameter to the controller
                    data: function (query) {
                        console.log(query)
                        return { search: query.term }
                    },
                    //processes the results from the JSON method and gives us the select list
                    processResults: function (data) {
                        console.log(data)
                        return {
                            results: JSON.parse(data)
                        };
                    }
                }
        });
    

    【讨论】:

    • 天哪!我抄的有点多。忘记多余的});
    • 您的网站是否上线,如果是,请提供链接:)
    猜你喜欢
    • 1970-01-01
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多