如何修复调用Yahoo Weather API时response.forEach is not a function错误
错误原因
forEach是仅数组类型支持的遍历方法,你请求的天气接口返回的根response是对象结构,直接对其调用forEach方法就会触发该类型错误。- 额外注意:你代码中用到的
Case_Fatality_Rate是疫情相关字段,天气接口不会返回该字段,需要替换为天气接口实际返回的属性。
修复方案
首先确认接口返回的天气预报列表存放在response.forecasts数组中,将遍历对象改为该数组即可,同时调整为接口实际支持的字段,修复后代码如下:
const settings = { "async": true, "crossDomain": true, "url": "https://yahoo-weather5.p.rapidapi.com/weather?location=izmir&format=json&u=f", "method": "GET", "headers": { "x-rapidapi-host": "yahoo-weather5.p.rapidapi.com", "x-rapidapi-key": "xxxxxxxxxxxxxxxxx" } }; $.ajax(settings).done(function (response) { var str = ''; // 遍历接口返回的forecasts天气预报数组 response.forecasts.forEach(item => { str += ' <tr>'; str += ' <td>' + item.day + '</td>'; str += ' <td>' + item.date + '</td>'; str += ' <td>' + response.sunset + '</td>'; // 日落数据在根对象下,不在forecasts子项里 str += ' <td>' + item.low + '°F / ' + item.high + '°F</td>'; // 替换为实际的温度字段 str += ' <td>' + item.text + '</td>'; // 天气状况字段 str += ' </tr>'; }); jQuery("#gridData").html(str); console.log(response); });
验证小技巧
如果不清楚接口返回结构,可以先在回调第一行加console.log(response),打开浏览器控制台查看完整返回结构,确认需要遍历的数组字段位置再写遍历逻辑即可。
内容的提问来源于stack exchange,提问作者exe
相关产品推荐
相关产品推荐

