javascript 如何使用ajax更新select2下拉列表中的数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19899983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:11:10  来源:igfitidea点击:

how to update data in select2 dropdown using ajax

javascriptjqueryajaxjquery-select2

提问by Herald Charley

I have a select2 dropdown for location.select2 data is initialised on page load.I want to update the data at regular intervals using ajax.But when I update the data of select2 the select2 dropdown becomes read only

我有一个用于 location.select2 数据的 select2 下拉列表在页面加载时初始化。我想使用 ajax 定期更新数据。但是当我更新 select2 的数据时,select2 下拉列表变为只读

    jQuery("#e10_2").select2({
        allowClear: true,
        minimumInputLength: 1,
        data:{ results: locationls, text: function(item) { return item.text; }},
        formatSelection: format,
        formatResult: format
    }); 

回答by Wallter

I don't really understand your question and think it needs some clarifying - but as far as I could understand (I ran into this problem and found your question when Googleing it...)

我不太明白你的问题,并认为它需要一些澄清 - 但据我所知(我遇到了这个问题并在谷歌搜索时发现了你的问题......)

When I first load the page I run the following JavaScript so that all of my drop-down select boxes are styled and using select2:

当我第一次加载页面时,我运行以下 JavaScript,以便我的所有下拉选择框都设置样式并使用 select2:

$('select').select2();

But as your title states, my code below works by updating the drop-down to a new set of data -where my /store/ajax_get_zonesfunction returns HTML for the options:

但正如您的标题所述,我下面的代码通过将下拉列表更新为一组新数据来工作 - 其中我的/store/ajax_get_zones函数为选项返回 HTML:

$(function() {
    $('#country').on('change', function() {
        $.post("/store/ajax_get_zones", {
            country_id: $('#country').val()
        }, function(e) {
            if (e)
                $("#state").html(e).select2();
        })
    });
});

All you have to do is call .select2()on the element after you update the data.

您所要做的就是.select2()在更新数据后调用该元素。

Screen Shots

屏幕截图

Start with the default United States:

从默认的美国开始:

Starting/Default United States

起始/默认美国

Then when you change the country the state drop-down changes as well (ajax updated the inner HTML of the original select while still themed to select2

然后,当您更改国家/地区时,状态下拉列表也会更改(ajax 更新了原始选择的内部 HTML,同时仍以 select2 为主题

Changing the country results in the changing of the state dropdown

更改国家会导致更改状态下拉列表