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

如何通过Ajax调用API获取并同时展示气温与天气描述?

解决天气API的属性访问与多数据展示问题

问题原因

你访问不到weather对象的description属性,是因为API返回的weather字段是数组类型,而非单个对象。需要先获取数组中的第一个元素,再访问其description属性。

修改后的代码

<span id="temp"></span>
<span id="weather"></span>
<script>
const getJSON = function(url, callback) {
    let xhr = new XMLHttpRequest();
    xhr.open('get', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      let status = xhr.status;
      if (status == 200) {
        callback(null, xhr.response);
      } else {
        callback(status);
      }
    };
    xhr.send();
};

getJSON('https://mm214.com/jsondemo.php', function(err, data) {
  if (err != null) {
    alert('Something went wrong: ' + err);
  } else {
    // 渲染气温,添加单位提升可读性
    document.getElementById("temp").innerHTML = `${data.main.temp}°C`;
    // 渲染天气描述:weather是数组,取第一个元素的description
    document.getElementById("weather").innerHTML = data.weather[0].description;
  }
});
</script>

关键说明

  • 访问天气描述必须使用data.weather[0].description:API返回的weather是包含天气信息对象的数组,第一个元素即为当前天气数据。
  • 可通过console.log(data)在浏览器控制台打印完整的API返回结构,方便核对字段层级关系。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 17:33:12