如何通过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
相关产品推荐
相关产品推荐

