首页 > 解决方案 > bootstrap-select 使用 ajax 设置选项文本

问题描述

我从 ajax url 设置选项文本有问题。

例如我有网址http://localhost:5000/api/test/calgroups

在这个网址中,我可以看到json所有组名的列表(可以更多)

["tes1","tes2","tes3","tes4","tes5","tes6"]

但我找不到一些信息如何设置,我的多选功能文本我想像这样

    <select class="selectpicker" name="MultiSelectGroup" id="ms1" multiple>
        <option id="gruop" >test1</option>
        <option id="gruop" >test2</option>
        <option id="gruop" >test3</option>
... (ant more)
    </select>

我在警报字段中获取文本值的代码(不需要显示,但也许会有所帮助)

$('.selectpicker').on('changed.bs.select', function () {

    selectedServices = $.map($(this).find("option:selected"), function(o) { return o["label"]; });
alert(selectedServices)


});

那么如何使用来自 ajax 链接的值设置我的选项字段呢?所有帮助将不胜感激

标签: javascripthtmlajax

解决方案


您可以使用 ajax 获取值并将它们作为选项插入,如下所示:

(请记住,这里是模拟取值的,它只是返回数组)

async function getValuesWithAjax() {
  return ["test1", "test2", "test3"];
}

$(function() {

  getValuesWithAjax().then(values => {
    values.forEach(value => {
      $(".selectpicker").append($("<option>")
        .val(value)
        .html(value)
      );
    });
  });


  $('.selectpicker').on('change', function() {
    selectedServices = $(this).val();
    alert(selectedServices)
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="selectpicker" name="MultiSelectGroup" id="ms1" multiple>
</select>


推荐阅读