无法将JSON内容解析到weatherArray变量,变量始终为空数组
为啥你的weatherArray总是空数组?
嘿,我一眼就看出问题所在啦!这都是异步请求的执行顺序搞的鬼~
你的代码里用的是异步的XMLHttpRequest,当你调用xhttp.send()之后,浏览器不会傻等着请求完成才继续执行代码,它会直接往下走。所以如果你在调用loadDoc()之后立刻去访问weatherArray,这时候请求还没拿到服务器的响应,weatherArray自然还是初始的空数组。
举个例子,要是你这么写肯定拿不到数据:
loadDoc(); console.log(weatherArray); // 这里输出[],因为请求还在后台跑呢!
几种靠谱的解决方案
1. 直接在回调里处理数据
既然数据只有在onreadystatechange回调触发时才准备好,那所有需要用到这个数据的逻辑,都直接放在这个回调里就行:
let weatherArray = []; function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { weatherArray = JSON.parse(this.responseText); // 在这里处理数据,比如打印或者渲染到页面 console.log(weatherArray); // 这里就能拿到正确的数据啦 renderWeatherToPage(weatherArray); // 假设你有个渲染页面的函数 } }; xhttp.open("GET", "https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12", true); xhttp.send(); }
2. 用回调函数传递数据
要是不想把所有逻辑都堆在回调里,你可以定义一个回调函数,把解析好的数据传进去,这样代码结构更清晰:
function loadDoc(callback) { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { const weatherData = JSON.parse(this.responseText); callback(weatherData); // 把数据传给外部的回调函数 } }; xhttp.open("GET", "https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12", true); xhttp.send(); } // 调用的时候传入处理逻辑 loadDoc(function(weatherArray) { console.log(weatherArray); // 这里妥妥拿到数据 // 做你需要的操作就行 });
3. 改用更现代的fetch API
XMLHttpRequest其实有点过时啦,现在更推荐用fetchAPI,它基于Promise,写法更简洁易懂:
function loadDoc() { return fetch("https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12") .then(response => response.json()) .catch(error => console.error('请求出错啦:', error)); } // 调用方式 loadDoc().then(weatherArray => { console.log(weatherArray); // 处理数据的逻辑放这里 }); // 或者用async/await,写起来像同步代码一样舒服 async function getWeather() { try { const response = await fetch("https://fcc-weather-api.glitch.me/api/current?lon=55&lat=12"); const weatherArray = await response.json(); console.log(weatherArray); // 处理数据 } catch (error) { console.error('请求出错:', error); } } getWeather();
内容的提问来源于stack exchange,提问作者João Araújo
相关产品推荐
相关产品推荐

