简体   繁体   English

select2 4.0.3中的动态加载选项

[英]Dynamic loading options in select2 4.0.3

Hi javascript experts. 嗨,JavaScript专家。

I'm trying to fetch a set of options via a ajax get reguest, and insert the results as a set of options in a select2 dropdown list. 我试图通过ajax获取请求获取一组选项,并将结果作为一组选项插入到select2下拉列表中。

Having looked at all the questions on SO regarding this, and followed the official select2 guide ( https://select2.github.io/examples.html#data ) leaves me a bit puzzled, i've extracted a simple example that illustrates the problem. 查看了关于此的所有问题,并遵循了官方的select2指南( https://select2.github.io/examples.html#data ),这让我有些困惑,我提取了一个简单的示例来说明问题。 Also tried using a hardcoded array instead of the data returned from the ajax call. 还尝试使用硬编码数组而不是从ajax调用返回的数据。

<html>

    <script type="text/javascript">
        $(function () {
            $("#ArbiterId").select2();

            FillArbiters(true);
        });

        function FillArbiters(eloOnly) {
            $.ajax({
                url: "/MasterData/Arbiters", dataType: "json",
                data: { 'eloOnly': eloOnly },
                type: "get",
                cache: false,
                success: function (data) {
                    console.log(data);
                    $("#ArbiterId").select2({ data: data.arbiters });
               //     $("#ArbiterId").select2({ data: [{ id: 0, text: 'dummy' }] });
                }
            });
        }
    </script>

    <body>
    <form>
        <select id="ArbiterId" name="ArbiterId"></select>
    </form>
    </body>

    </html>

Can anyone tell me what i'm doing wrong? 谁能告诉我我在做什么错?

The output from the ajax looks like this: ajax的输出如下所示:

{
  "success": true,
  "arbiters": [
    {
      "text": " name 1",
      "id": 11446
    },
    {
      "text": "name 2",
      "id": 10786
    }
.....

Turns out i was trying to initialize the #ArbiterId as a select2 box twice, which are not allowed (would be nice if select2 informed me about that) 原来我试图两次将#ArbiterId初始化为一个select2框,这是不允许的(如果select2通知我有关信息,那将很好)

The correct way to dynamically change the options is to first destroy the select2 box, and then recreate it, eg changing 动态更改选项的正确方法是先破坏select2框,然后重新创建它,例如,更改

$("#ArbiterId").select2({ data: data.arbiters });

to

$("#ArbiterId").select2('destroy').empty().select2({ data: data.arbiters });

more information about this topic can be found here: https://github.com/select2/select2/issues/2830 有关此主题的更多信息,请参见: https//github.com/select2/select2/issues/2830

(answering my own question in case someone else with the same problem comes around) (回答我自己的问题,以防其他人遇到同样的问题)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM