javascript - 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 链接的值设置我的选项字段呢?所有帮助将不胜感激
解决方案
您可以使用 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>
推荐阅读
- c# - C# MVVM 模型图消息中介或 INotifyPropertyChanged?
- android - android构建所需的最少文件
- c++ - 将 `std::valarray` 集成到数据结构中
- html - 在浏览器调整大小时,大图像不会缩小到 CSS 网格容器
- angular - 7 - 8 条动态路线
- postgresql - 为 Postgres 安装 SSL 的 SSH 密钥
- javascript - 如何计算所有存储的 cookie?
- excel - 如何将列单元格提取为单张图片?
- javascript - 如何使用 express-winston 在 msg 对象中记录请求正文 (req.body)?
- c++ - 带功能支持的调车场算法