使用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
相关产品推荐
相关产品推荐

