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

使用JS fetch()填充select下拉菜单失败,求排查代码问题

问题排查与修复

核心问题是你代码里假设的返回数据结构和实际接口返回的不匹配:

你请求的states.json返回的是直接的州对象数组(比如[{"abbr":"AL","state":"Alabama"}, ...]),但你的代码里却在判断res.status,并尝试遍历res.data——这两个属性在实际返回的数组里根本不存在,导致循环代码完全没执行,下拉菜单自然没被填充。

修正后的代码

const states = document.getElementById('states');
states.innerHTML = '<option value="" disabled selected>Select State</option>';

fetch('https://jarednewnam.com/test/states.json')
  .then(res => res.json())
  .then(stateList => {
    // 直接遍历返回的数组即可
    stateList.forEach(state => {
      const option = document.createElement('option');
      option.value = state.abbr;
      option.textContent = state.state; // 简化文本节点创建,用textContent更便捷
      states.appendChild(option);
    });
  })
  .catch(err => console.error('请求出错:', err)); // 建议添加catch捕获错误,方便调试

额外调试建议

  • 在then(res => res.json())的回调里先执行console.log(stateList),确认返回数据的实际结构,避免凭假设写代码。
  • 加上catch块,能捕获请求过程中可能出现的网络错误或JSON解析错误,不会像之前一样无报错提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 03:40:22