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

如何将API返回的站点数据填充到<select>下拉框并生成对应option选项

代码问题排查及修复方案

存在的问题:

  • 未初始化html变量:代码中直接使用html +=拼接字符串,但之前没有声明和初始化html变量,会触发引用错误,导致渲染逻辑终止
  • 循环内使用未定义变量:遍历allstations数组时,没有声明对应的取值变量key、obj,也没有从数组元素中读取站点属性,无法正确拼接option内容
  • 可选优化:HTML结构缺少div、section的闭合标签,虽然部分浏览器会自动补全,但不符合代码规范,建议补全

修正后代码

HTML代码:

<section class="container">
  <div class="item">
    <p>list</p>
    <select id="subwaystation"> 
    </select>
  </div>
</section>

JS代码:

var apiStations = "https://api-ratp.pierre-grimaud.fr/v4/stations/metros/8";

function req1() {
  fetch(apiStations, {
    method: "get"
  })
  .then(response => response.json())
  .then(data => {
    let allstations = data.result.stations;
    // 初始化存储option的字符串变量
    let html = '';
    for(var i = 0; i < allstations.length; i++) {
      // 读取当前遍历的站点信息,slug作为提交值,name作为显示文本
      const station = allstations[i];
      html += `<option value="${station.slug}">${station.name}</option>`
    }
    document.getElementById("subwaystation").innerHTML = html;
  })
  // 新增异常捕获,方便后续排查请求类问题
  .catch(err => console.error('站点请求失败:', err))
}
req1();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:57:02