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

使用Ajax调用iRail API时出现Cannot read property错误求助

解决iRail API调用中无法读取standardname的问题

你遇到的错误是因为对iRail API返回的JSON结构理解有误,咱们一步步来修正:

问题根源

当你调用https://api.irail.be/stations/?format=json时,返回的JSON结构并不是直接把车站数据放在根对象的索引0里,而是所有车站都包裹在station数组中。举个返回数据的简化示例:

{
  "version": "1.0",
  "station": [
    {"id": "BE.NMBS.008812005", "standardname": "Brussels-Central", "name": "Brussel-Centraal/Bruxelles-Central"},
    // 更多车站数据...
  ]
}

你原来的代码res['0'].standardname试图直接访问根对象的0属性,但这个属性根本不存在,自然会报错“无法读取未定义的standardname属性”。

修正后的代码

下面是调整后的完整代码,我还加了一些更稳健的配置:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$.ajax({
  method: "GET",
  url: "https://api.irail.be/stations/?format=json",
  dataType: "json", // 明确指定返回类型为JSON,让jQuery自动解析
})
.done(function(res) {
  // 正确访问station数组的第一个元素
  if (res.station && res.station.length > 0) {
    console.log(res.station[0].standardname);
  } else {
    console.log("未获取到车站数据");
  }
})
.fail(function(err) {
  // 增加请求失败的错误处理
  console.error("请求出错:", err);
});
</script>

关键改动点

  • 把res['0']改成res.station[0],对应API返回的正确结构
  • 增加了dataType: "json",确保jQuery正确解析返回的JSON数据
  • 加入了简单的判空逻辑,避免当station数组为空时再次报错
  • 增加了.fail()回调,方便排查请求失败的情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:47:20