You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用API获取数据生成tom-select选项失败,请求修复

修复TomSelect无法渲染API获取的下拉选项问题

问题根源分析

  1. 异步执行顺序错误:renderCourses()是异步函数,调用后不会立即完成数据填充,但TomSelect紧接着就初始化了——此时options数组还是空的,自然无法渲染选项。
  2. 语法错误:options.Push()中的Push首字母大写,JS数组方法名是小写的push,这会导致无法向数组添加元素。
  3. 变量未声明:allCourses、result、f未用let/const声明,会隐式创建全局变量,存在潜在的冲突风险。

修复方案(两种可选)

方案1:等待数据加载完成后再初始化TomSelect

将数据获取与组件初始化合并为一个异步流程,确保数据准备好后再创建下拉组件:

<div class="p-4">
  <select id="select-junk" placeholder="Start Typing..."></select>
</div>
async function getCourses() {
    try {
        let res = await fetch("https://covid19.mathdro.id/api/countries");
        return await res.json();
    } catch (error) {
        console.log(error);
    }
}

async function initTomSelect() {
    const allCourses = await getCourses();
    // 容错处理:避免API返回数据异常导致报错
    if (!allCourses?.countries) return;
    
    // 用map快速生成符合要求的选项数组
    const options = allCourses.countries.map(country => ({
        iso: country.iso2,
        name: country.name
    }));

    // 初始化TomSelect
    new TomSelect('#select-junk',{
        maxItems: null,
        maxOptions: 100,
        valueField: 'iso',
        labelField: 'name',
        searchField: 'name',
        sortField: 'name',
        options: options,
        create: false
    });
}

// 执行初始化流程
initTomSelect();

方案2:先初始化空组件,再动态加载选项

适合需要先显示空下拉框,再异步加载数据的场景:

<div class="p-4">
  <select id="select-junk" placeholder="Start Typing..."></select>
</div>
async function getCourses() {
    try {
        let res = await fetch("https://covid19.mathdro.id/api/countries");
        return await res.json();
    } catch (error) {
        console.log(error);
    }
}

// 先初始化空的TomSelect组件
const tomSelect = new TomSelect('#select-junk',{
    maxItems: null,
    maxOptions: 100,
    valueField: 'iso',
    labelField: 'name',
    searchField: 'name',
    sortField: 'name',
    options: [],
    create: false
});

// 异步加载并更新选项
async function loadOptions() {
    const allCourses = await getCourses();
    if (!allCourses?.countries) return;
    
    const options = allCourses.countries.map(country => ({
        iso: country.iso2,
        name: country.name
    }));
    
    // 动态添加选项到TomSelect
    tomSelect.addOption(options);
}

loadOptions();

内容的提问来源于stack exchange,提问作者Dimas Alfiansyah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 07:40:35