【问题标题】:filling a Select2 select box with an array populated by an ajax query使用由 ajax 查询填充的数组填充 Select2 选择框
【发布时间】:2018-12-27 02:50:39
【问题描述】:

我想将 Select2 用于选择框,该框由对 api 的 ajay 查询填充,只需一次调用 api。每次击键后无需再次查询api。

我尝试使用这个线程来实现它: How to pre-load an array via ajax and use it for select2? 但我仍然无法在下班后让它工作-.-

我的代码:

<script type="text/javascript">
        $(document).ready(function() {
            var linkableSystems = [];
            $.ajax({
                url: 'ulrHere'
            }).done(function(data) {
                linkableSystems = data.results;
                console.log(linkableSystems);
                $('#SelectLinkedSystemToAdd').select2('enable', true);
            });
            $('#SelectLinkedSystemToAdd').select2({
                dataType: 'json',
                data: function () { return { results: linkableSystems }; }
            },
                console.log(linkableSystems)
            ).select2('enable', false);
        });


    </script>
&lt;select id="SelectLinkedSystemToAdd" class="form-control"&gt;&lt;/select&gt;

api返回:

{
    "results": [
        {
            "text": "demo CLIENT 1",
            "id": 1
        },
        {
            "text": "demo CLIENT 2",
            "id": 2
        }
    ]
}

我尝试使用 select2 ajax 调用填充选择框,它可以工作。但我不能让它工作,所以它只做 1 个单一的 api 调用。 根据控制台,linkableSystems一开始是空的:

[]
​length: 0

然后由ajax请求填充:

(2) […]
​0: Object { text: "demo CLIENT 1", id: 1 }
​1: Object { text: "demo CLIENT 2", id: 2 }

遗憾的是,Select2 没有按照我上面链接的线程中的建议选择这些更改。

谁能帮我解决这个问题? 如果您需要更多信息,请询问!

谢谢!

【问题讨论】:

    标签: javascript jquery-select2 angularjs-select2


    【解决方案1】:

    请记住,这些请求是异步的。

    $.ajax({
      url: 'ulrHere'
    }).done(function(data) {
      $('#SelectLinkedSystemToAdd').select2({data: data.results});
    });
    

    应该可以解决问题,因为您会在数据实际可用时更新 select2。如果您在 select2 有时有点不确定之前初始化了它。您可能需要执行 $('#SelectLinkedSystemToAdd').select2('destroy') 并再次使用数据重新启动选择。

    【讨论】:

    • 我想我误解了链接的帖子。我认为选择 2 会在使用 data: function () { return { results: linkableSystems }; } 时进行更改。但是您的解决方案有效,而且很好而且简短。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    • 2014-12-10
    • 2017-05-13
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    相关资源
    最近更新 更多