从 JSON 填充下拉列表

Populate dropdown from JSON

我试图简单地用来自 API 的 JSON 响应填充下拉列表。

let dropdown = $('#LA_picker');

dropdown.empty();

dropdown.append('<option selected="true" disabled>Choose State/Province</option>');
dropdown.prop('selectedIndex', 0);

const url = 'https://api.coronavirus.data.gov.uk/v1/data?filters=areaType%3DnhsTrust%3Bdate%3D2020-12-20&structure=%7B%22name%22:%22areaName%22,%22code%22:%22areaCode%22%7D&format=json&page=1';

$.getJSON(url, function(data) {
  $.each(data.data, function(key, entry) {
    dropdown.append($('<option></option>').val(entry.name).html(entry.name));
    console.log(entry.name);
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="LA_picker" class="selectpicker" data-live-search="true"></select>

打开网页时,下拉菜单有“选择State/Province”,但没有其他选项。请注意,我已将 console.log(entry.name); 放在那里以检查控制台输出,这是成功的,并按预期给出了所有条目的名称。

我可能做错了什么?

来自您的评论:

Seems the class "selectpicker" is what breaks it. This is from the Bootstrap-select plugin.

因为在 <select> 元素上有一个 bootstrap selectpicker 实例...必须在收到 ajax 请求的结果后实例化该实例。

您实际上实例化了 selectpicker class。删除它并在 getJSON 回调中添加 dropdown .selectpicker();,在 $.each 循环之后。

ajax 请求需要一些时间来解决...并且 selectpicker 正在根据原始 <select> 的内容向 DOM 添加一些新元素。这就是插件必须在 getJSON 回调中实例化的原因。

bootstrap-select documentation

let dropdown = $('#LA_picker');

dropdown.empty();

dropdown.append('<option selected="true" disabled>Choose State/Province</option>');
dropdown.prop('selectedIndex', 0);

const url = 'https://api.coronavirus.data.gov.uk/v1/data?filters=areaType%3DnhsTrust%3Bdate%3D2020-12-20&structure=%7B%22name%22:%22areaName%22,%22code%22:%22areaCode%22%7D&format=json&page=1';

$.getJSON(url, function(data) {
  $.each(data.data, function(key, entry) {
    dropdown.append($('<option></option>').val(entry.name).html(entry.name));
    console.log(entry.name);
  })
  dropdown.selectpicker();
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/i18n/defaults-*.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script>

<select id="LA_picker" data-live-search="true"></select>