使用Vanilla JS从RESTful API填充下拉菜单遇TypeError问题求解
问题解决:正确调用API填充下拉菜单
错误原因分析
TypeError: data.map is not a function:你直接对API返回的整个响应对象调用了map方法,但该对象并非数组——真正的日期数据数组嵌套在data.floodguard_dates.rows路径下。- 无法获取
clickedDates.dataprog:说明你没有正确定位到rows数组中的元素,必须先提取该数组再进行后续操作。
完整实现代码
// 获取页面中的下拉菜单元素 const dateSelect = document.getElementById('date-select'); // 发起API请求并处理数据 fetch('http://194.141.118.43:3010/dates') .then(response => { if (!response.ok) { throw new Error('请求API失败'); } return response.json(); }) .then(data => { // 提取正确的日期数据数组 const dateRows = data.floodguard_dates.rows; // 遍历数组生成下拉选项 dateRows.forEach(row => { const option = document.createElement('option'); option.value = row.datprog; option.textContent = row.datprog; dateSelect.appendChild(option); }); }) .catch(error => { console.error('数据加载失败:', error); }); // 监听下拉菜单选择事件,获取选中的datprog值 dateSelect.addEventListener('change', (e) => { const selectedDataprog = e.target.value; console.log('选中的日期:', selectedDataprog); // 此处可添加选中后的业务逻辑 });
关键注意事项
- 严格匹配API返回结构:必须通过
data.floodguard_dates.rows路径获取目标数组,不能直接对顶层data对象使用数组方法。 - 增加错误处理:通过
response.ok判断请求状态,配合catch块捕获异常,避免请求失败时无反馈。 - 安全创建DOM元素:使用
createElement生成选项,比拼接HTML字符串更安全、易维护。
内容的提问来源于stack exchange,提问作者Ben Johnson
相关产品推荐
相关产品推荐

